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

Posted

技术标签:

【中文标题】如何在 discord.py 中使用 sqlite3 配置欢迎事件?【英文标题】:How to configure welcome event with sqlite3 in discord.py? 【发布时间】:2020-12-17 06:10:30 【问题描述】:

我正在尝试使用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!")

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

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'

我已经尝试了很多方法来解决这个问题,但遗憾的是我不能。

【问题讨论】:

不应该是ctx.guild.id 而不是ctx.guild_id 吗? 我知道这将是一个愚蠢的错误,但没想到会这么愚蠢 ????,谢谢顺便说一句 【参考方案1】:

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

【讨论】:

以上是关于如何在 discord.py 中使用 sqlite3 配置欢迎事件?的主要内容,如果未能解决你的问题,请参考以下文章

Discord.py SQLite3 禁用词系统 - 问题

尝试使用 sqlite3 向我的 discord.py 机器人添加自定义前缀

discord py SQLite 警告命令 db 错误

如何在 discord.py 中使用高级命令处理

如何在嵌入 discord.py 中使用 markdown 语法发送图像

如何在 discord.py 中嵌入如下图所示的按钮? [关闭]