即使代码正常,Bot也停止工作

2024-10-02 10:30:18 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我第一次编写一个discord机器人,我一直在学习教程,但我想制作一个独特的游戏,所以我试着自己制作。但经过一段时间的纠结之后,我意识到我的代码中唯一有效的部分是mcguccy是一个白痴,而不是客户端。命令部分工作

import discord
from discord.ext import commands

client = commands.Bot(command_prefix='!')


@client.command()
async def ping1(ctx):
    await ctx.send("pong!")


@client.event
async def on_ready():
    await client.change_presence(status=discord.Status.online, activity=discord.Game("cranking 90s on shitters"))
    print("bot is ready!")


@client.event
async def on_member_join(member):
    print(f'{member} has joined :weary:.')


@client.event
async def on_member_remove(member):
    print(f'{member} has left :weary:')


@client.command()
async def helb(ctx):
    await ctx.send('@everyone look at this idiot')


@client.command()
async def ping(ctx):
    await ctx.send(f'here you go: {round(client.latency * 1000)}ms')


@client.command()
async def commands(ctx):
    await ctx.send('1. helb it will help you. 2. ping it will tell you the bots ping. ')


@client.command()
async def overlord(ctx):
    await ctx.send("muah hah hah YOUR SERVER IS MINE")

keywords = ["mcguccy is an idiot", "kick mcguccy", "i want to nuke the server"]


@client.event
async def on_message(message):
    for i in range(len(keywords)):
        if keywords[i] in message.content:
            for j in range(20):
                await message.channel.send(f"@everyone someone has spammed :weary:")

Tags: clienteventsendmessageasyncondefawait
1条回答
网友
1楼 · 发布于 2024-10-02 10:30:18

这里有几点需要注意:

您的client变量是Bot类型,而不是Client类型。

client = commands.Bot(command_prefix='!')

这意味着您需要使用@bot装饰器而不是@client装饰器:

@client.command()
async def helb(ctx):
    ...
# Becomes
@bot.command()
async def helb(ctx):
    ...

永远不会调用.run()方法。

因此,bot的事件循环不会启动。您需要初始化Client event loop,以便bot可以侦听要传递的命令:

if __name__=='__main__':
    client.run(TOKEN)

该代码必须是文件中运行的最后一条语句,因为它正在阻塞

.run()命令需要一个API令牌。

如果您还没有令牌,您可以通过creating a bot account获得所述令牌。如果确实有一个参数,则需要将其作为第一个参数传递给.run()方法

相关问题 更多 >

    热门问题