Discord.py-RuntineWarning:从未等待协程

时间:2020-11-08 12:26:01

标签: python async-await discord.py python-asyncio coroutine

我的代码

from discord.ext import commands
import discord
import asyncio
import math
import aiosqlite
import logging

logger = logging.getLogger('discord')
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)

class TagCommand(commands.Cog):

    def __init__(self, client):
        self.client = client
        self.emojis = ['⏪', '⏩', '⏹️']
        self.pagination_value = 3
        self.max_pages = 100

    @commands.group(name='tag', invoke_without_command=True)
    async def tag(self, ctx):
        await ctx.send(".tag create Name Content")

    @tag.command(name="create")
    async def tag_create(self, ctx, name=None, *, content=None):
        try:
            if name == None or content == None:
                await ctx.send("Missing Arguments")
            else:
                async with aiosqlite.connect('s137_guild_values') as db:
                    await db.execute('INSERT INTO tag_list (guild_id, name, content) VALUES(?, ?, ?)', (ctx.guild.id, name, content))
                    await db.commit()
                await ctx.send("Done")
        except Exception as e:
            await ctx.send(e)

    @commands.command()
    async def tags(self, ctx):
        print("Command Initiated")
        names = []
        print("1")
        async with aiosqlite.connect('s137_guild_values') as db:
            print("2")
            async with db.execute('SELECT name FROM tag_list WHERE guild_id = ?', (ctx.guild.id,)) as cursor:
                print("3")
                async for row in cursor:
                    print("4")
                    value = row
                    value = list(value)
                    names.append(value[0])
                    print("5")
        print("6")
        if len(names) != 0:
            STOP = False
            print("7")
            pagination_dict = {}
            amount_tags = len(names)
            for x in range(1, self.max_pages):
                if (math.ceil(amount_tags / x) == self.pagination_value):
                    needed_pagination = x
                    print("8")
                    break
            current_page = 1
            print("9")
            var = 1
            counter = 0
            counter_all = 0
            counter_all_eq = len(names)
            print("10")
            index = 0
            while True:
                pagination_dict['Page {}'.format(var)] = {}
                msg = ""
                for x in range(0, (len(names))):
                    msg += '• {}\n'.format(names[index])
                    names.remove(names[index])
                    counter += 1
                    counter_all += 1
                    if (len(names) == 0) and (counter != self.pagination_value):
                        counter = self.pagination_value
                    if counter == self.pagination_value:
                        counter = 0
                        pagination_dict['Page {}'.format(var)]['Content'] = msg
                        msg = ""
                        var += 1
                        break
                if (var >= needed_pagination) and (counter_all == counter_all_eq):
                    break
            txt = "Current Page: {}/{}".format(current_page, needed_pagination)
            embed = discord.Embed(title="Tags ({})".format(amount_tags), description=pagination_dict['Page {}'.format(str(current_page))]['Content'], timestamp=ctx.message.created_at, colour=discord.Colour.blue())
            embed.set_footer(text=txt)
            msg = await ctx.send(embed=embed)
            for ele in self.emojis:
                await msg.add_reaction(ele)
            async def Main():
                while STOP == False:
                    def check(reaction, user):
                        return str(reaction.emoji) and user == ctx.author

                    try:
                        reaction, user = await self.client.wait_for('reaction_add', timeout=60.0, check=check)
                    except asyncio.TimeoutError:
                        msg_2 = await msg.channel.fetch_message(msg.id)
                        for reaction in msg_2.reactions:
                            await msg_2.remove_reaction(reaction, reaction.user)
                        STOP = True
                    if reaction.emoji == '⏪':
                        if current_page != 1:
                            current_page -= 1
                            embed = discord.Embed(title="Tags ({})".format(amount_tags), description=pagination_dict['Page {}'.format(current_page)]['Content'], timestamp=ctx.message.created_at, colour=discord.Colour.blue())
                            txt = "Current Page: {}/{}".format(current_page, needed_pagination)
                            embed.set_footer(text=txt)
                            await msg.edit(embed=embed)
                            await msg.remove_reaction(reaction, ctx.author)
                        else:
                            await msg.remove_reaction(reaction, ctx.author)
                    elif reaction.emoji == '⏩':
                        if current_page != (needed_pagination):
                            current_page += 1
                            embed = discord.Embed(title="Tags ({})".format(amount_tags), description=pagination_dict['Page {}'.format(current_page)]['Content'], timestamp=ctx.message.created_at, colour=discord.Colour.blue())
                            txt = "Current Page: {}/{}".format(current_page, needed_pagination)
                            embed.set_footer(text=txt)
                            await msg.edit(embed=embed)
                            await msg.remove_reaction(reaction, ctx.author)
                        else:
                            await msg.remove_reaction(reaction, ctx.author)
                    elif reaction.emoji == '⏹️':
                        await msg.delete()
                        STOP = True
            asyncio.run(Main())
        else:
            await ctx.send("There Are No Tags On This Server!")

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

错误

/usr/lib/python3.7/asyncio/events.py:88: RuntimeWarning: coroutine 'TagCommand.tags.<locals>.Main' was never awaited
  self._context.run(self._callback, *self._args)

这应该是用于标签的自定义分页系统。

它曾经工作过一次,所以代码很好,但是显然我之前有一个关于代码阻塞的问题,所以我继续阅读并仍然不理解它。

这是我尝试学习的知识以及如何解决它的结论,现在我又遇到了另一个错误。 任何帮助将不胜感激

0 个答案:

没有答案