簡體   English   中英

如何修復我的 Discord Bot 中的 datetime 命令?

[英]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.

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