I am programming a discord bot that will send an embed to a separate channel when someone uses a command to prevent abuse and so our admins can keep an eye on usage.
I have this code:
#client.command()
#has_permissions(manage_messages=True)
async def purge(ctx, amount=5):
await ctx.channel.purge(limit = amount + 1) # Plus one is so that it also deletes the players purge message
embed = discord.Embed(title="Purged Channel", description="", colour=0xe74c3c, timestamp=datetime.utcnow())
embed.set_author(name="CS Moderation", icon_url="https://cdn.discordapp.com/attachments/938857720268865546/938863881726615602/ca6.png")
embed.add_field(name="Staff Member", value=ctx.author.mention, inline=False)
embed.set_footer(text="Made by HeadOfTheBacons#6666", icon_url=None)
channel = client.get_channel("938898514656784404") #Change ID of logging channel if needed
await channel.send(embed = embed)
When I run this, I cannot get the embed to be sent to a different channel. I have tried checking other posts already but I have not had much luck at all. I have no errors when I use the command or try to run the bot. The point here is when someone uses the command to make a new embed, set up the preferences, specify the specific channel ID where I want this embed to be sent to, and have the computer send it off to that channel. However, it is not sending. Why is my code not working? What do I need to change in my code to make this send a message?
Check if you have an on_command_error function in your program, it could be the reason of your no error problem.
Also not that the embed.footer can't be None, and the client.get_channel requires an Integer.
So you can try out the following code, it should work:
from datetime import datetime
import discord
from discord.ext import commands
from discord.ext.commands import has_permissions
client = commands.Bot(command_prefix="prefix")
#client.command()
#has_permissions(manage_messages=True)
async def purge(ctx, amount=5):
await ctx.channel.purge(limit=amount + 1) # Plus one is so that it also deletes the players purge message
embed = discord.Embed(title="Purged Channel", description="", colour=0xe74c3c, timestamp=datetime.utcnow())
embed.set_author(name="CS Moderation", icon_url=client.user.avatar_url)
embed.add_field(name="Staff Member", value=ctx.author.mention, inline=False)
embed.set_footer(text="Made by HeadOfTheBacons#6666")
channel = client.get_channel(938898514656784404) # Change ID of logging channel if needed
await channel.send(embed=embed)
client.run("TOKEN")
Related
Is my code supposed to be working fine? because it was doing well before. Right now after I start running the code. And input and relay the messages . It wouldnt be sending it anymore. And would getting the channel name better rather than getting the channel id? if getting the channel id is better, What should I replace with if channel.name in? , If my code is fine does that mean the issue is gonna be the discod permissions?
#commands.has_permissions(kick_members=True)
async def alert(ctx, *, msg): #ALERT
for guild in client.guilds:
role = get(guild.roles, name = 'RayGunOptions Alerts') # roles
for channel in guild.channels:
if channel.name in ('π’π½ππΆπΌπ»-ππΉπ²πΏππ','gunvir-gay'): # change for the list of channel names you got in your discord server
one = Button(style=ButtonStyle.URL, label='Twitter', url="https://twitter.com/RayGunsOptions")
two = Button(style=ButtonStyle.URL, label='Discord', url="https://discord.gg/6Fh4MTZN")
three = Button(style=ButtonStyle.URL, label='Trading Journal', url="https://tradingjournal.com")
embed=discord.Embed(title= ':moneybag: **Option Alert** :moneybag:', description= (msg), url='https://twitter.com/RayGunsOptions', color=0x33FF9F, timestamp=datetime.datetime.utcnow())
"""embed.set_author(name="Crypto Alert", icon_url = ctx.author.avatar_url)""" #Top left name # IGNORE
embed.set_thumbnail(url='https://pbs.twimg.com/profile_images/1383574983645962246/kD6PNI_L_400x400.jpg')
embed.set_footer(icon_url = ctx.author.avatar_url, text='Powered by Duck Programming',)
await channel.send(f"{role.mention}")
await channel.send(embed=embed)
await channel.send(
'** **',
components=[
[one,]
]
)
If you have a on_message_function in your code please add this in the end:
await self.bot.process_commands(message) # or client if you don't use bot
Source: https://discordpy.readthedocs.io/en/stable/faq.html?highlight=on_message#why-does-on-message-make-my-commands-stop-working
Also if your command is not in your cog please don't do:
commands.command()
Instead do:
bot.command() #or client.command()
I have a discord bot that will scrape covid information and send the information to a specific discord server's text channel. But how can I make the bot to send the data to all server's text channel which it connected ?
Currently I'm specifying which text channel:
channel = client.get_channel(694814300220686399) # replace with channel id of text channel in discord
client.loop.create_task(channel.send("abc")
Instead of only sending to a specific server's text channel, I want to send it to every channel it has access to.
For this, you'll need a channel with a common name in all the servers... Let's say the name of the channel is 'general'. Then, you can do it this way...
import discord
from discord.ext import commands
for server in client.guilds:
requiredChannel = discord.utils.get(server.channels, name = 'general')
await requiredChannel.send("Your message")
you can do like this:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix=".")
#client.event()
async def on_ready():
#client.command()
async def send_info(ctx , heading, content):
for guild in client.guilds:
for channel in guild.channels:
if channel == "Covid Alert":
channel.send("**"+Heading+"**\n"+content)
sorry for a messy code it could have been done better i think
If I understood your question correctly this should fit your needs.
for channel in guild.text_channels:
if channel.permissions_for(guild.me).send_messages:
await channel.send("Message")
Example "covid" commmand
#client.command()
async def covid(ctx):
guild = ctx.guild
for channel in guild.text_channels: #loops through all channels
if channel.permissions_for(guild.me).send_messages: #checks for permissions
await channel.send("Message") #sends your message
I'm currently coding a bot in discord.py that does mod commands like kick, etc. I'm trying to make a command that you can suggest something to the server like they make a channel called suggestion-channel, when they do the command it sends it to that channel. I have a command that sends a message to a specific channel for bot suggestions, but that's the closest I've gotten. below is the code that I have for the suggest command in cogs, yes I use command handling.
#commands.command()
async def suggest(self ,ctx , *, suggestion):
embed = discord.Embed(title=f"Suggestion from {ctx.author.name}", description=suggestion, color=discord.Color.blue())
embed.set_footer(text=f"Suggestion created by {ctx.author}")
channel = discord.utils.get(message.server.channels, name="suggestion-channel")
message = await channel.send(embed=embed)
await message.add_reaction("β
")
await message.add_reaction("β")
await ctx.message.delete()
await ctx.send("Thank you for your suggestion!")
First of all, you're not getting the channel in an on_message event, or using a user's message to get the server's channels. You'll have to replace message with ctx. Secondly, ctx.server is no longer valid since discord.py's migration. It would now be known as ctx.guild, which you can read about in their docs.
channel = discord.utils.get(message.server.channels, name="suggestion-channel")
# change this to:
channel = discord.utils.get(ctx.guild.channels, name="suggestion-channel")
Otherwise, if you find that any of your other commands are not working, you may have not processed your on_message event. You can view questions on how to solve this:
Why does on_message stop commands from working?
await process_commands(message) [docs]
discord.py #bot.command() not running
I'm making a discord bot and I want it to send a message whenever it joins a new guild.
However, I only want it to send the message in the #general channel of the guild it joins:
#client.event
async def on_guild_join(guild):
chans = guild.text_channels
for channel in chans:
if channel.name == 'general':
await channel.send('hi')
break
The problem that I have noticed is that guild.text_channels only returns the name of the very first channel of the server. I want to iterate through all channels and finally send message only on the #general channel.
What's the workaround for it?
There are a couple ways you can do this.
Here's an example using utils.get():
import discord # To access utils.get
#client.event
async def on_guild_join(guild):
channel = discord.utils.get(guild.text_channels, name="general")
await channel.send("Hi!")
Or if the guild has a system_channel set up, you can send a message there:
#client.event
async def on_guild_join(guild):
await guild.system_channel.send("Hi!")
You can create checks for both of these, but bear in mind that some servers might not have a text channel called general or a system channel set up, so you may receive some attribute errors complaining about NoneType not having a .send() attribute.
These errors can be avoided with either an error handler or a try/except.
References:
Guild.system_channel
utils.get()
I am working on a discord bot in python3 (discord.py 1.3.3, discord 1.0.1) and I have a need to delete a user message, but I can't figure out how to call the coroutine properly.
I have looked at some other threads, and tried reviewing the documentation (and the discord.py docs) but I haven't been able to figure it out.
Here's what I'm testing with:
import discord
from discord.ext import commands
TOKEN = os.getenv('DISCORD_TOKEN')
bot = commands.Bot(command_prefix='!')
#bot.command(name='deleteme', help='testing command for dev use')
async def deleteme(ctx):
msg = ctx.message.id
print(f'DEBUG: message id is {msg}')
await msg.delete
# await ctx.delete(msg, delay=None) #nope
# await ctx.delete_message(ctx.message) #nope
# await bot.delete_message(ctx.message) #nope
# await command.delete_message(ctx.message) #nope
# await discord.Client.delete_message(msg) #nope
Running this returns the console debug message with an ID number, but the message isn't deleted. If I add a debug print line after await msg.delete it doesn't return. So this tells me where the script is hanging. That said, I still haven't been able to figure out what the proper command should be.
The bots server permissions include "manage messages"
In order to delete a message, you have to use the discord.Message object, for example, you would do:
await ctx.message.delete()
The delete() coroutine is a method of discord.Message