discord.py on_guild_join 事件
discord.py on_guild_join event
好的,所以我试图让我的 discord 机器人在加入公会时按名称创建两个特定的频道,但它并没有这样做。它也没有抛出错误。
这是我的代码:
@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 如果有帮助,请重写。我也在 运行 我的 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))
问题很可能在于您没有使用正确的公会对象。并使用不正确的 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. But in order to create text channels in a guild. You need a guild object。
如果我们查看事件的输入:
async def on_guild_join(self, guild):
我们看到我们确实得到了 guild object. It is now really easy to 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
好的,所以我试图让我的 discord 机器人在加入公会时按名称创建两个特定的频道,但它并没有这样做。它也没有抛出错误。
这是我的代码:
@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 如果有帮助,请重写。我也在 运行 我的 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))
问题很可能在于您没有使用正确的公会对象。并使用不正确的 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. But in order to create text channels in a guild. You need a guild object。 如果我们查看事件的输入:
async def on_guild_join(self, guild):
我们看到我们确实得到了 guild object. It is now really easy to 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