Reputation:
Ok, so I'm trying to make my discord bot create two specific channels by name upon joining a guild, but it's not doing that. It's not throwing errors either.
Here is my code:
@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`.")
I am using Discord.py Rewrite if it helps. I am also running this event in my Events.py
Cog. Any help would be much appreciated.
Here is my entire Events.py
Cog as well in case the error is somewhere in there.
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))
Upvotes: 2
Views: 10899
Reputation: 1173
The problem most likely lies in the fact that you dont use the correct guild object. And use an incorrect ctx instead (The ctx is from the client not the guild).
The following code is wrong:
cli = self.client
ctx = cli.get_context
await ctx.create_text_channel("📯announcements-and-suggestions")
await ctx.create_text_channel("💼log")
You get a ctx object (which is useless as its from the client and not the guild). But you dont have a guild object. But in order to create text channels in a guild. You need a guild object. If we look at the input of the event:
async def on_guild_join(self, guild):
We see that we do get a guild object. It is now really easy to create channels (if you have the permissions):
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
If you are going to use more events in the future. I highly suggest you take a look at what the events can give you through their inputs. It mostly gives you relevant objects that spare you from doing unneccessary stuff (getting ctx of client, which is also wrong as it is not from the guild but the client).
For more info about the on_guild_join event: https://discordpy.readthedocs.io/en/latest/api.html?highlight=on_guild_join#discord.on_guild_join
Upvotes: 4