python - 如何在我的 Discord Bot 中修复我的 datetime 命令?
问题描述
我最近开始了解 Discord Bots 并尝试自己制作一个,我已经掌握了一些基础知识,但无法让代码的新部分正常工作,这应该得到当前的日期时间并且想知道我做错了什么。
编辑:这目前托管在 Heroku 上,所以我不知道如何检查错误
import discord
from datetime import datetime
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
@client.event
async def on_member_join(member):
print(f'{member.name} has joined the server')
channel = client.guilds[0].get_channel(745404752161931266)
print(channel)
await channel.send(f'{member.name} has joined the server')
@client.event
async def on_member_remove(member):
print(f'{member.name} has left the server')
channel = client.guilds[0].get_channel(745404752161931266)
print(channel)
await channel.send(f'{member.name} has left the server')
@client.event
async def on_message(message):
channel = client.guilds[0].get_channel(765757497155649567)
if message.content.find("!hello") != -1:
await message.channel.send("Hello!")
@client.event
async def on_message(message):
now = datetime.now()
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
if message.content.find("!datetime") != -1:
await message.channel.send("date and time =", dt_string)
client.run('[my_token]')
解决方案
您不能拥有多个相同的侦听器,您必须将整个代码放在一个
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!hello'):
# ...
elif message.content.startswith('!datetime'):
# ...
一个更好的选择是使用commands.Bot
,这里有一个例子:
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f"Logged in as {bot.user}")
@bot.command()
async def hello(ctx):
await ctx.send('Hello!')
# To invoke: `!hello`
bot.run('token')
这个类是 discord.Client 的子类,因此你可以用 discord.Client 做的任何事情都可以用这个机器人做。
但是如果你真的想坚持下去,discord.Client
你可以创建自定义事件,client.dispatch('name of the event', *args)
遗憾的是没有关于它的文档。
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!hello'):
# Dispatching the custom event
client.dispatch('hello', message)
@client.event
async def on_hello(message):
"""Notice how the event it's called `on_hello` not `hello` and
takes the same arguments that we specified in `client.dispatch`"""
await message.channel.send('Hello!')
还要检查您的 heroku 应用程序的日志:
heroku logs -a {name of the app}
or
heroku logs -a {name of the app} --tail
推荐阅读
- pine-script - pinescript中是否有process_orders_on_open之类的东西?
- amazon-s3 - AWS Cloud S3 并使用 Tableau 检索文件
- typescript - 根据主ID和子ID合并数组内的对象
- php - PHP - 防止在具有父对象的对象中循环引用
- javascript - 通过 DOM 设置 src 与比较 src 值
- html - CSS悬停被强制 - 应用于孩子
- android - 为什么 Zoom Meeting 应用程序显示在用于共享 GEO 位置意图的可用应用程序列表中?
- r - 如何将0到1之间的值向量映射到R中的彩色条?
- string - Fortran 90 打印出一个空字符串
- oracle - Hackerrank 问题 PLSQL 员工未分配到任何部门