【问题标题】:discord.py on_guild_join eventdiscord.py on_guild_join 事件
【发布时间】:2020-06-30 09:51:53
【问题描述】:

好的,所以我试图让我的不和谐机器人在加入公会时按名称创建两个特定频道,但它没有这样做。它也不会抛出错误。

这是我的代码:

@commands.Cog.listener()
    async def on_guild_join(self, guild):
        cli = self.client
        ctx = cli.get_context
        await ctx.create_text_channel("????announcements-and-suggestions")
        await ctx.create_text_channel("????log")               
        general = find(lambda x: x.name == '????announcements-and-suggestions',  guild.text_channels)
        if general and general.permissions_for(guild.me).send_messages:
            await ctx.send(f"Hello {guild.name}! I am {self.client.user.display_name}. Thank you for inviting me.\n\nTo see what commands I have available type `r?help`.\nIf you want to see my available AutoResponse Triggers type `gethelp`.")

如果有帮助,我正在使用 Discord.py Rewrite。我也在我的Events.py Cog 中举办这个活动。任何帮助将不胜感激。

这是我的整个Events.py Cog,以防错误出现在其中。

import discord
from discord.ext import commands
from discord import Activity, ActivityType
from discord.utils import find
import json
import random


def load_counters():
    with open('./data/counters.json', 'r') as f:
        counters = json.load(f)
    return counters


def save_counters(counters):
    with open('./data/counters.json', 'w') as f:
        json.dump(counters, f, indent=4)

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

    @commands.Cog.listener()
    async def on_ready(self):
        cli = self.client.user
        await self.client.change_presence(activity=discord.Streaming(name=f"r?help | in {len(self.client.guilds)} servers", url="https://www.twitch.tv/discord"))
        print(" ")
        print("License")
        print(" ")
        print("Copyright (c) Joshua Lewis")
        print(" ")
        print("Permission is hereby granted, free of charge, to any person obtaining a copy")
        print("of this software and associated documentation files (the Software), to deal")
        print("in the Software without restriction, including without limitation the rights")
        print("to use, copy, modify, merge, publish, distribute, sublicense, and/or sell")
        print("copies of the Software, and to permit persons to whom the Software is")
        print("furnished to do so, subject to the following conditions:")
        print(" ")
        print("The above copyright notice and this permission notice shall be included in all")
        print("copies or substantial portions of the Software.")
        print(" ")
        print("THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR")
        print("IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,")
        print("FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE")
        print("AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER")
        print("LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,")
        print("OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE")
        print("SOFTWARE.")
        print("Connecting to Discord API")
        print("...")
        print("......")
        print(".........")
        print(f"Logged in as : {cli.name}#{cli.discriminator}")
        print("Collecting list of connected guilds")
        print("...")
        print("......")
        print(".........")
        print("Connected Guilds:")
        print(f"{self.client.guilds}")


    @commands.Cog.listener()
    async def on_guild_join(self, guild):
        cli = self.client
        ctx = cli.get_context
        await ctx.create_text_channel("????announcements-and-suggestions")
        await ctx.create_text_channel("????log")               
        general = find(lambda x: x.name == '????announcements-and-suggestions',  guild.text_channels)
        if general and general.permissions_for(guild.me).send_messages:
            await ctx.send(f"Hello {guild.name}! I am {self.client.user.display_name}. Thank you for inviting me.\n\nTo see what commands I have available type `r?help`.\nIf you want to see my available AutoResponse Triggers type `gethelp`.")

    @commands.Cog.listener()
    async def on_message_delete(self, message):
        ctx = self.client.get_context
        guild = message.author.guild
        author = message.author
        ch = message.channel
        cli = self.client.user
        content = message.content
        orange = discord.Color.dark_orange()
        for channel in guild.channels:
            if str(channel.name) == "????log":
                msg_del = str(f"""```css\n{content}```""")
                aut_name = str(f"""```css\n{author.display_name}```""")
                ch_name = str(f"""```css\n{ch.name}```""")
                embed = discord.Embed(color=orange, timestamp=ctx.message.created_at)
                embed.set_author(name="Message Deleted", icon_url=cli.avatar_url)
                embed.add_field(name=f"Message", value=msg_del, inline=False)
                embed.add_field(name=f"Message Author", value=aut_name, inline=False)
                embed.add_field(name=f"Channel", value=ch_name, inline=False)
                embed.set_thumbnail(url=author.avatar_url)
                embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
                message.embed = (content)
                await channel.send(embed=embed)
                print(f'message: {content} by {author.display_name} was deleted in {ch.name}')



    @commands.Cog.listener()
    async def on_member_join(self, ctx, member):
        guild = ctx.guild
        cli = self.client.user
        gold = discord.Color.dark_gold()
        user_join = str(f"""```css\n{member} has entered {guild.name}.```""")
        for channel in guild.channels:
            if str(channel.name) == "????log":                
                embed = discord.Embed(color=gold)
                embed.set_author(name=cli.display_name, icon_url=cli.avatar_url)
                embed.add_field(name="Use Joined", value=user_join, inline=False)
                embed.set_thumbnail(url=cli.avatar_url)
                embed.set_image(url=member.avatar_url)
                embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
                await channel.send(embed=embed)

    @commands.Cog.listener()
    async def on_member_remove(self, ctx, member):
        guild = ctx.guild
        cli = self.client.user
        red = discord.Color.dark_red()
        for channel in guild.channels:
            if str(channel.name) == "????log":                
                user_left = str(f"""```css\n{member} has left {guild.name}""")
                embed = discord.Embed(color=red)
                embed.set_author(name=cli.display_name, icon_url=cli.avatar_url)
                embed.add_field(name="User Left", value=user_left, inline=False)
                embed.set_image(url=member.avatar_url)
                embed.set_thumbnail(url=cli.avatar_url)
                embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
                await channel.send(embed=embed)

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

【问题讨论】:

    标签: python python-3.x discord.py-rewrite


    【解决方案1】:

    问题很可能在于您没有使用正确的公会对象。并改用不正确的 ctx(ctx 来自客户端而不是公会)。

    以下代码错误:

        cli = self.client
        ctx = cli.get_context
        await ctx.create_text_channel("?announcements-and-suggestions")
        await ctx.create_text_channel("?log") 
    

    你得到一个 ctx 对象(它来自客户端而不是公会,它是无用的)。但是你没有guild object。但是为了在公会中创建文本频道。你需要一个guild object。 如果我们看一下事件的输入:

    async def on_guild_join(self, guild):
    

    我们看到我们确实得到了一个guild 对象。现在很容易create channels(如果你有权限的话):

    async def on_guild_join(self, guild):
        await guild.create_text_channel("?announcements-and-suggestions")
        await guild.create_text_channel("?log")
        # the rest of your code
    

    如果您将来要使用更多活动。我强烈建议你看看这些事件可以通过他们的输入给你什么。它主要为您提供相关对象,使您免于做不必要的事情(获取客户端的 ctx,这也是错误的,因为它不是来自公会而是来自客户端)。

    有关 on_guild_join 活动的更多信息:https://discordpy.readthedocs.io/en/latest/api.html?highlight=on_guild_join#discord.on_guild_join

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-12
      相关资源
      最近更新 更多