簡體   English   中英

如何讓機器人加入頻道並在聊天中回復 discord.py

[英]How to make a bot join a channel and respond in chat discord.py

我最近才開始學習編碼,以便在 python 中制作 discord 機器人。 我已經分別使用了這兩段代碼並且它們都起作用了,但是當嘗試將它們一起使用時,只有消息起作用,並且機器人不會加入語音通道。

當我輸入 join 命令時沒有出現錯誤。

但是,我似乎找不到錯誤。 如果有人可以查看我的代碼並找到我出錯的地方,將不勝感激,謝謝。

@client.command
async def join(ctx):
  if (ctx.author.voice):
    channel = ctx.message.author.voice.channel
    await channel.connect()
  else:
    await ctx.send("I am terribly sorry, but I cannot join you as you are not in a voice channel.")

@client.event
async def on_message(message):
  if message.author == client.user:
    return

  msg = message.content
  
  if any(word in msg for word in stimulus_words):
    await message.channel.send(random.choice(stimulus))

首先,對於 Discord.py 的新手來說,您的代碼看起來不錯

問題來自您的async def join(ctx):沒有被 discord注冊為命令。 這可以通過在 function 頂部添加@client.command()來完成。 這樣,當有人使用 $join($ = 您為機器人選擇的前綴)時,它將被識別並與上下文一起調用。 你可以在這里找到更多信息

另外,我建議您研究Cogs ,這是一種組織代碼的好方法

預編輯:我看到您編輯了代碼以在 function 頂部添加裝飾器,但是您缺少( )所以這就是我認為它不起作用的原因

當您在 discord.py 中發出命令時,您必須輸入@client.command() (調用函數),這與@client.event不同。

這就是您的 function 應該是:

@client.command()
async def join(ctx):
  if (ctx.author.voice):
    channel = ctx.message.author.voice.channel
    await channel.connect()
  else:
    await ctx.send("I am terribly sorry, but I cannot join you as you are not in a voice channel.")

如果您只是想讓機器人響應某些提示,請嘗試以下操作:

@client.event
async def on_message(message):
     if message.author == client.user:
         return

     if '#your prompt here' in message.content:
              await message.channel.send('#your response here')

或者,如果您希望機器人僅查看消息的開頭,請嘗試:

@client.event
async def on_message(message):
     if message.author == client.user:
         return


     if  message.content.startswith('your prompt here'):
              await message.channel.send('#your response here')

如果您遇到問題,我還可以為您提供如何讓隨機選擇的東西起作用的示例。 我對編碼也很陌生,幾周前剛剛創建了我的機器人。 把它們放在一起玩得很開心。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM