如何在discord.py中使用sqlite3配置欢迎事件?

时间:2020-08-28 09:58:57

标签: python sqlite discord discord.py

我正在尝试用sqlite3配置我的欢迎事件。我编写了以下代码:

import discord
from discord.ext import commands, tasks
import discord.utils
import asyncio
import datetime
import sqlite3
class WelCog(commands.Cog, name='Welcome') :

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

    @commands.Cog.listener()
    async def on_member_join(self,member):
        db = sqlite3.connect('main.sqlite')
        cursor = db.cursor()
        cursor.execute(f"SELECT channel_id FROM main WHERE guild_id = {member.guild.id}")
        result =  cursor.fetchone()
        if result is None:
            return
        else:
            cursor.execute(f"SELECT msg FROM main WHERE guild_id = {member.guild.id}")
            result1 =  cursor.fetchone()
            members = len(list(member.guild.members))
            mention = member.mention
            user = member.name
            guild=member.guild
            embed = discord.Embed(color=0x0ff7dc, description=str(result1[0]).format(members=members, mention=mention, user=user, guild=guild))
            embed.set_thumbnail(url=f"{member.avatar_url}")
            embed.set_author(name=f"{member.name}", icon_url=f"{member.avatar_url}")
            embed.set_author(name=f"{member.guild}", icon_url=f"{member.guild.icon_url}")
            channel = self.bot.get_channel(id=int(result[0]))
            await channel.send(embed=embed)
    
    
    @commands.group(invoke_without_command=True)
    async def welcome(self,ctx):
        await ctx.send('Available Setup Commands: \nwelcome channel <#channel>\n welcome text <message>')
    @welcome.command()
    async def channel(self, ctx, channel:discord.TextChannel):
        if ctx.message.author.guild_permissions.manage_messages:
            db = sqlite3.connect('main.sqlite')
            cursor = db.cursor()
            cursor.execute(f"SELECT channel_id FROM main WHERE guild_id = {ctx.guild.id}")
            result =  cursor.fetchone()
            if result is None:
                sql = ("INSERT INTO main(guild_id, channel_id) VALUES(?,?)")
                val = (ctx.guild.id, channel.id)
                await ctx.send(f"Channel has be set to {channel.mention}")
            elif result is not None:
                sql = ("UPDATE main SET channel_id = ? WHERE guild_id = ?")
                val = (channel.id, ctx.guild_id)
                await ctx.send(f"Channel has been updated to {channel.mention}")
            cursor.execute(sql, val)
            db.commit()
            cursor.close()
            db.close()

    @welcome.command()
    async def text(self, ctx,*, text):
        if ctx.message.author.guild_permissions.manage_messages:
            db = sqlite3.connect('main.sqlite')
            cursor = db.cursor()
            cursor.execute(f"SELECT msg FROM main WHERE guild_id = {ctx.guild.id}")
            result =  cursor.fetchone()
            if result is None:
                sql = ("INSERT INTO main(guild_id, msg) VALUES(?,?)")
                val = (ctx.guild.id, text)
                await ctx.send(f"Message have been set to `{text}`")
            elif result is not None:
                sql = ("UPDATE main SET msg = ? WHERE guild_id = ?")
                val = (text, ctx.guild_id)
                await ctx.send(f"Message have been updated to `{text}`")
            cursor.execute(sql, val)
            db.commit()
            cursor.close()
            db.close()
def setup(bot):
    bot.add_cog(WelCog(bot))
    print("Welcome cog is loaded!")

welcome命令可以正常工作,但是当我尝试设置默认的欢迎频道或默认的欢迎消息时,会显示以下错误:

Ignoring exception in command welcome text:
Traceback (most recent call last):
  File "C:\Users\Rohit\AppData\Roaming\Python\Python37\site-packages\discord\ext\commands\core.py", line 83, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\Rohit\Desktop\discord bots\quotient\cogs\welcome.py", line 71, in text
    val = (text, ctx.guild_id)
AttributeError: 'Context' object has no attribute 'guild_id'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\Rohit\AppData\Roaming\Python\Python37\site-packages\discord\ext\commands\bot.py", line 892, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Rohit\AppData\Roaming\Python\Python37\site-packages\discord\ext\commands\core.py", line 1234, in invoke
    await ctx.invoked_subcommand.invoke(ctx)
  File "C:\Users\Rohit\AppData\Roaming\Python\Python37\site-packages\discord\ext\commands\core.py", line 797, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\Rohit\AppData\Roaming\Python\Python37\site-packages\discord\ext\commands\core.py", line 92, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'guild_id'

我已经尝试了很多方法来解决此问题,但遗憾的是我没有。

1 个答案:

答案 0 :(得分:1)

如果将ctx.guild_id替换为ctx.message.guild.id,则必须解决问题。