Discord 机器人代码不起作用(python)。我该如何解决?
Posted
技术标签:
【中文标题】Discord 机器人代码不起作用(python)。我该如何解决?【英文标题】:Discord bot codes not working (python). How can I fix it? 【发布时间】:2021-06-06 19:43:10 【问题描述】:我最近开始编写代码,并决定制作一个 Discord 机器人是一种很好、有趣的学习方式。所以我做了一些编码,从 Youtube 视频中学习,一切都很顺利,但现在我的代码都没有工作,机器人基本上没用。有人可以看看这段代码并告诉我是什么问题
import discord
import os
import requests
import json
import random
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as 0.user'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('Hello'):
await message.channel.send('Hi!')
client.run(os.getenv('TOKEN'))
sad_words = ["sad","alone","scared","depressed","SAD","Sad"]
starter_encouragements = [
"You got this. I know you do ????",
"I know it's hard, but you'll get through this :)",
]
def get_quote():
response = requests.get("https://zenquotes.io/api/random")
json_data = json.loads(response.text)
quote = json_data[0]['q'] + " -" + json_data[0]['a']
return(quote)
@client.event
async def on_ready():
print('We have logged in as 0.user'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
msg = message.content
if message.content.startswith('inspire'):
quote = get_quote()
await message.channel.send(quote)
if any(word in msg for word in sad_words):
await message.channel.send(random.choice(starter_encouragements))
client.run(os.getenv('TOKEN'))
非常感谢
【问题讨论】:
我不想粗鲁,但正确的术语是code
而不是 codes
,在编程上下文中的代码被认为是不可数名词,例如 sand
或 water
.你不会说I have some sands
吧?这里也一样。
【参考方案1】:
不幸的是,多个on_message
事件不起作用。
您一次只能有一个事件,因此您必须合并这些事件。这看起来像这样:
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('Hello'): # First event
await message.channel.send('Hi!')
[Shortened]
if message.author == client.user:
return
[Shortened]
await message.channel.send(random.choice(starter_encouragements)) # Last event
我还会删除您的第二个 on_ready
事件,因为它没用。
您确实可以拥有多个client.command()
函数,但这不计入事件。
或许也可以看看下面的帖子:Why multiple on_message events will not work
【讨论】:
以上是关于Discord 机器人代码不起作用(python)。我该如何解决?的主要内容,如果未能解决你的问题,请参考以下文章