Discord.py on_guid_Join事件 [英] discord.py on_guild_join event

查看:20
本文介绍了Discord.py on_guid_Join事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我试着让我的不和谐机器人在加入一个公会后,通过名字创建两个特定的频道,但它没有做到这一点。它也没有抛出错误。

以下是我的代码:

@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.

To see what commands I have available type `r?help`.
If you want to see my available AutoResponse Triggers type `gethelp`.")

如果有帮助,我正在使用Discord.py重写。我也在我的Events.py齿轮中运行此事件。如有任何帮助,我们将不胜感激。

这也是我的整个Events.py齿轮,以防出现错误。

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.

To see what commands I have available type `r?help`.
If 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
{content}```""")
                aut_name = str(f"""```css
{author.display_name}```""")
                ch_name = str(f"""```css
{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
{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
{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))

推荐答案

问题很可能在于您没有使用正确的行会对象。并改用错误的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_GUID_JOIN事件的详细信息:https://discordpy.readthedocs.io/en/latest/api.html?highlight=on_guild_join#discord.on_guild_join

这篇关于Discord.py on_guid_Join事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆