Discord.py --> channel.mention

2019-02-19 09:17发布

I'm trying to make a bot for a discord server that simply listens for specific messages, deletes them and then refers the user to a different text channel (in a clickable link by mentioning it)

Here's what I have now:

import Discord
import asyncio


client = discord.Client()


@client.event
async def on_message(message):
    msg = '{0.author.mention}\nWrong text channel\nUse '.format(message)
    if message.content.startswith('!p'):
        await client.delete_message(message)
        await client.send_message(message.channel, msg)
    return


client.run('')

Ideally, I'd also want to search through a list with startswith() instead of just ('!p') & to ignore all messages from a specific text channel as well but I'm not sure how to do those either

1条回答
做自己的国王
2楼-- · 2019-02-19 09:48

Sure, just add text_channel = client.get_channel('1234567890') and reference its mention with text_channel.mention (where 1234567890 is the id of the channel you want to link to)

So the code would end up looking something like this

@client.event
async def on_message(message):
  text_channel = client.get_channel('1234567890')
  msg = '{0.author.mention}\nWrong text channel\nUse {1.mention}'.format(message,text_channel)
  if message.content.startswith('!p'):
      await client.delete_message(message)
      await client.send_message(message.channel, msg)
  return

Regarding your second question, you could do something like this

  arr = ['!p','!a','!b']
  for a in arr:
    if message.content.startswith(a):
      break
  else:
    return

and remove the if message.content.startswith('!p'): altogether

To ignore a specific channel just do if message.channel.id == "9876543210": at the top of the function (9876543210 is the id of the channel you want to ignore commands from)
With those changes the code looks like this

@client.event
async def on_message(message):
  if message.channel.id == "9876543210":
    return
  arr = ['!p','!a','!b']
  for a in arr:
    if message.content.startswith(a):
      break
  else:
    return
  text_channel = client.get_channel('1234567890')
  msg = '{0.author.mention}\nWrong text channel\nUse {1.mention}'.format(message,text_channel)
  await client.delete_message(message)
  await client.send_message(message.channel, msg)
  return
查看更多
登录 后发表回答