[英]How do I fix my datetime command in my Discord Bot?
我最近开始了解 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')
这个 class 是 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.