python discord 机器人事件无效

python discord bot event not working

我的距离计算器事件不起作用。 它应该(如果工作的话)计算 2 个地方之间的距离并给出玩家应该等待多长时间直到他去那里的消息(口袋妖怪去相关) 没有给我错误,它什么都不做。 我尝试了不同的方法,但 none 似乎有效。 任何人都可以帮助我吗?太棒了!

from discord.ext import commands
import discord
import gpxpy.geo
import math
import asyncio

client = discord.Client(command_prefix='kaikai*')

@client.async_event
async def on_ready():
    print("Logged in as:")
    print(client.user.name)
    print("ID:")
    print(client.user.id)
    print("Ready to use!")

@client.async_event
async def on_message(message) :
    if message.author == client.user:
        return
    elif message.content.startswith("kaikai*test") :
        await client.send_message(message.channel, "BOT READY!")

@client.async_event
class Distance:
    """Calculate the distance between two coordinates."""
    def __init__(self, client):
        self.client = client

    @commands.command(pass_context=True)
    async def distance(self, ctx, *, message):
        """Calculate the distance between two coordinates and also provide you with a cooldown time."""
        # Your code will go here

        def error_embed_1(self):
            embed=discord.Embed(
                title="Error:",
                description="Not enough data given. Did you give 4 different coordinates, seperated by spaces?",
                color=0x207cee)

            return embed
        def error_embed_2(self):
            embed=discord.Embed(
                title="Error:",
                description="Your message is invalid. Please use this format\n``!distance <num1> <num2> <num3> <num4>``\nWhich would look like this: ``!distance 51.301597 -0.598019 51.270664 -0.594132``",
                color=0x207cee)
            return embed

        def calc_embed(msg, msg2):
            embed=discord.Embed(
                title="",
                description=" ",
                color=0x207cee)
            embed.add_field(
                name="**Calculated Distance:**",
                value="{} Kilometers".format(msg),
                inline=False)
            embed.add_field(
                name="**Cooldown Timer:**",
                value="{} ".format(msg2),
                inline=False)
            return embed

        def calculate(lon1, lat1, lon2, lat2):
            dist = gpxpy.geo.haversine_distance(lat1, lon1, lat2, lon2)
            dist = dist/1000
            dist = round(dist, 2)

            return dist

        def cooldown(dist):
            time = " "


            if dist >= 1500:
                time = "120 minutes"

            elif dist >= 1403 and dist <= 1500:
                time = "120 minutes"

            elif dist >= 1344 and dist <= 1403:
                time = "119 minutes"

            elif dist >= 1300 and dist <= 1344:
                time = "117 minutes"

            elif dist >= 1221 and dist <= 1300:
                time = "112 minutes"

            elif dist >= 1180 and dist <= 1221:
                time = "109 minutes"

            elif dist >= 1020 and dist <= 1180:
                time = "101 minutes"

            elif dist >= 1007 and dist <= 1020:
                time = "97 minutes"

            elif dist >= 948 and dist <= 1007:
                time = "94 minutes"

            elif dist >= 897 and dist <= 948:
                time = "90 minutes"

            elif dist >= 839 and dist <= 897:
                time = "88 minutes"

            elif dist >= 802 and dist <= 839:
                time = "83 minutes"

            elif dist >= 751 and dist <= 802:
                time = "81 minutes"

            elif dist >= 700 and dist <= 751:
                time = "76 minutes"

            elif dist >= 650 and dist <= 700:
                time = "73 minutes"

            elif dist >= 600 and dist <= 650:
                time = "69 minutes"

            elif dist >= 550 and dist <= 600:
                time = "65 minutes"

            elif dist >= 500 and dist <= 550:
                time = "61 minutes"

            elif dist >= 450 and dist <= 500:
                time = "58 minutes"

            elif dist >= 400 and dist <= 450:
                time = "54 minutes"

            elif dist >= 350 and dist <= 400:
                time = "49 minutes"

            elif dist >= 328 and dist <= 350:
                time = "48 minutes"

            elif dist >= 300 and dist <= 328:
                time = "46 minutes"

            elif dist >= 250 and dist <= 300:
                time = "41 minutes"

            elif dist >= 201 and dist <= 250:
                time = "36 minutes"

            elif dist >= 175 and dist <= 201:
                time = "33 minutes"

            elif dist >= 150 and dist <= 175:
                time = "31 minutes"

            elif dist >= 125 and dist <= 150:
                time = "28 minutes"

            elif dist >= 100 and dist <= 125:
                time = "26 minutes"

            elif dist >= 90 and dist <= 100:
                time = "24 minutes"

            elif dist >= 80 and dist <= 90:
                time = "23 minutes"

            elif dist >= 70 and dist <= 80:
                time = "22 minutes"

            elif dist >= 60 and dist <= 70:
                time = "21 minutes"

            elif dist >= 50 and dist <= 60:
                time = "20 minutes"

            elif dist >= 45 and dist <= 50:
                time = "19 minutes"

            elif dist >= 40 and dist <= 45:
                time = "18 minutes"

            elif dist >= 35 and dist <= 40:
                time = "17 minutes"

            elif dist >= 30 and dist <= 35:
                time = "16 minutes"

            elif dist >= 25 and dist <= 30:
                time = "14 minutes"

            elif dist >= 20 and dist <= 25:
                time = "11 minutes"

            elif dist >= 15 and dist <= 20:
                time = "8 minutes"

            elif dist >= 10 and dist <= 15:
                time = "6 minutes"

            elif dist >= 8 and dist <= 10:
                time = "4 minutes"

            elif dist >= 5 and dist <= 8:
                time = "3 minutes"

            elif dist >= 4 and dist <= 5:
                time = "2 minutes"

            elif dist >= 3 and dist <= 4:
                time = "2 minutes"

            elif dist >= 2 and dist <= 3:
                time = "1 minutes"

            elif dist and dist <= 1:
                time = "48 seconds"

            return time

        bool = True
        List = str(message)
        var = List.split(" ")
        try:
            lat1 = float(var[0])
            long1 = float(var[1])

            lat2 = float(var[2])
            long2 = float(var[3])

        except IndexError:
            msg = error_embed_1(self)
            bool = False
        except ValueError:
            msg = error_embed_2(self)
            bool = False

        if bool == True:
            calc = calculate(long1, lat1, long2, lat2)
            cooldown = cooldown(calc)
            msg = calc_embed(calc, cooldown)
        await client.send(embed=msg)


client.run("mytokenhere")

尝试将所有 @client.async_event 更改为 @client.event。您可以在示例中看到 here 这是正确的用法。

由于您有一个 on_message 事件,您必须指定必须处理的命令。这是通过在 on_message 事件中调用 process_commands(message) 来完成的。这不是默认完成的。 async 分支的文档是 here, while for the rewrite branch it's here.

您创建的Distance class也没有加载(据我所知,如果我错了请指正)。我建议将其移动到一个单独的文件中,然后将其加载到您的主机器人文件中。下面是如何完成此操作的示例,其中 bot.py 是运行机器人的主文件,cog.py 包含带有 add 命令的示例 class。 bot.py 还包括 on_message 事件和 process_commands(message) 来说明它的用法。

bot.py

from discord.ext import commands

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

client.load_extension('cog')

@client.event
async def on_ready():
    print('client ready')

@client.command()
async def ping():
    await client.say('Pong')

@client.event
async def on_message(message):
    if message.content == 'Hello'
        await client.send_message(message.channel, 'Hello')

    await client.process_commands(message)

client.run('TOKEN')

cog.py

from discord.ext import commands

class TestCog:

    def __init__(self, bot):
        self.bot = bot
        self.counter = 0

    @commands.command()
    async def add(self):
        self.counter += 1
        await self.bot.say('Counter is now %d' % self.counter)


def setup(bot):
    bot.add_cog(TestCog(bot))