python-3.x Discord bot在一定时间后断开并离线

pjngdqdw  于 2023-11-20  发布在  Python
关注(0)|答案(1)|浏览(161)

我的机器人保持在线约10至15分钟,之后它会离线,并随机重新上线,并在几分钟后崩溃

bot.py(示例网站)

import os
import asyncio
import discord
from discord.ext import commands
from decouple import config
from django.core import management
from manage import init_django
import json

init_django()
management.call_command('makemigrations')
management.call_command('migrate')

# with open('data.json', 'r', encoding='utf-8') as data_file:
#   data = json.load(data_file)
#   management.call_command('loaddata', 'data.json')

client = commands.Bot(command_prefix='-', intents=discord.Intents.all(),
                      application_id=...)

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

@client.event
async def on_disconnect():
    print('Disconnected') # I always get this message

async def load():
    for filename in os.listdir('./cogs'):
        if filename.endswith('.py'):
            client.load_extension(f'cogs.{filename[:-3]}')

async def main():
    await load()
    await client.start(config("TOKEN"))

asyncio.run(main())

字符串

breedings.py(示例网站)

import discord
from discord.ext import commands
from db.models import Monster
from channels.db import database_sync_to_async
from django.db.models import Q

@database_sync_to_async
def get_monster_breedings(name, rarety):
    monster = Monster.objects.filter(
        Q(name_translations__portuguese_name__icontains=name) |
        Q(name_translations__english_name__icontains=name), rarety__name=rarety
    ).prefetch_related('name_translations', 'rarety').first()

    if monster:
        prefetch_list = ['monster_1', 'monster_2', 'monster_3', 'island']
        prefetch_list += ['monster_1__name_translations',
                          'monster_2__name_translations',
                          'monster_3__name_translations']
        return list(monster.breedings.all().prefetch_related(*prefetch_list))
    return []

class Breedings(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.slash_command(name='ping', description='ping')
    async def ping(self, ctx: discord.ApplicationContext):
        await ctx.respond('pong')

    @commands.slash_command(name='breeding')
    @discord.option(name='rarety', choices=['Common', 'Rare', 'Epic'])
    async def breeding(self,
                       ctx,
                       monster: str,
                       rarety: str):
        breedings = await get_monster_breedings(name=monster, rarety=rarety)
        if not breedings:
            return await ctx.respond('Nada encontrado ;-;')

        monster_obj = breedings[0].monster
        embed = discord.Embed(url=str(monster_obj.url), title=monster_obj.name)
        embed.set_thumbnail(
            url=monster_obj.image_url,)

        default_times, enhancend_times = set(), set()
        for breed in breedings:
            m1, m2, m3 = breed.monster_1, breed.monster_2, breed.monster_3
            if breed.monster_3:
                value = f'Any({m1}, {m2}, {m3})'
            elif m2 is None:
                value = f'{m1} + Three elements'
            else:
                value = f'{m1} + {m2}'

            embed.add_field(name=breed.island or 'any island',
                            value=value, inline=False)
            default_times.add(breed.default_time)
            enhancend_times.add(breed.enhanced_time)

        embed.set_footer(
            text=f'Tempo padrão: {"; ".join(map(str, default_times))}\n'
                 f'Melhorado: {"; ".join(map(str, enhancend_times))}')

        await ctx.respond(embed=embed)

def setup(client):
    client.add_cog(Breedings(client))


我一直在寻找相关的东西了几天,我发现的最接近的事情是,这可能是一个问题的不和谐API,但没有办法解决它
当我设法捕获错误消息时,它类似于:discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

wwodge7n

wwodge7n1#

有几件事说不通。
1.在bot启动之前,您已在事件循环中将load()添加为异步
1.你在异步函数中使用client.start(),但你从来没有将它添加到循环中。如果你要将它添加到循环中,它看起来像:

try:
    loop.run_until_complete(start(*args, **kwargs))
except KeyboardInterrupt:
    loop.run_until_complete(close())
    # cancel all tasks lingering
finally:
    loop.close()

字符串
上面的代码相当于bot.run(),可以在Pycord文档中找到。
如果你不知道你在做什么关于client.start(),最好只是使用client.run()代替。
(我交替使用client和bot,但类应该是discord.ext.commands.Bot()

相关问题