Discord Bot 可以发送到特定频道而不每次都指定频道 ID

时间:2021-04-11 09:52:34

标签: python discord discord.py bots

我目前正在尝试通过将 Discord 服务器机器人用于课堂目的来开发交互式活动。我在这方面相当新,但已经掌握了事物的基本要点,但我确实有一个问题。我已经能够让我的机器人使用非常棒的频道 ID 向特定频道发送消息。问题是这在编码中会很混乱,因为目前我必须为每个单独的通道复制整个代码串。有没有办法把它整理成一组整洁的代码? 目前它看起来像这样:

if (message.channel.id == insertchannelid1):
  channel = client.get_channel(insertchannelid1)
  if message.content.startswith('hello'):
    await channel.send('lets begin')
    await channel.send('I cant seem to see the word hidden here, can you use your flashlight to help me?')
    await message.channel.send(file=discord.File('Spotlight_demo.exe'))
  if message.content.startswith('あか'):
    await channel.send('あか! Thank you! That must have to do with this...')
    

if (message.channel.id == insertchannelid2):
  channel = client.get_channel(insertchannelid2)
  if message.content.startswith('hello'):
    await channel.send('lets begin')
    await channel.send('I cant seem to see the word hidden here, can you use your flashlight to help me?')
    await message.channel.send(file=discord.File('Spotlight_demo.exe'))
  if message.content.startswith('あか'):
    await channel.send('あか! Thank you! That must have to do with this...')

它可以工作,但正如您所看到的,除了开头确定频道 ID 的代码外,它们实际上是相同的。任何整理此内容的帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

您可以将所有目标频道放在一个列表中,并检查频道 ID 是否在所述列表中:

accepted_channels = [insertchannelid1, insertchannelid2]
if message.channel.id in accepted_channels:
  if message.content.startswith('hello'):
    await message.channel.send('lets begin')
    await message.channel.send('I cant seem to see the word hidden here, can you use your flashlight to help me?')
    await message.channel.send(file=discord.File('Spotlight_demo.exe'))
  if message.content.startswith('あか'):
    await message.channel.send('あか! Thank you! That must have to do with this...')