Python Discord bot delete users message - python

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

Related

How to solve this "discord.client logging in using static token" error

my code was running perfectly for some time but it stopped suddenly with an unexpected token error and also i tried adding an image to the rich presence of my bot but it doesn't seem to be working and also i did my whole in replit
The error!
import discord
from webserver import keep_alive
import os
intents = discord.Intents.all()
client = discord.Client(intents=intents)
welcome_channel = None
prefix = "&"
#client.event
async def on_ready():
print(f"Logged in as {client.user}!")
await client.change_presence(status= discord.Status.dnd,
activity = discord.Activity(type=discord.ActivityType.playing,
assets={
'large_text': 'details',
'large_image': 'https://cdn.discordapp.com/attachments/998612463492812822/1063409897871511602/welcome.png',
},
name = "Dynamically",
details = "Dreams of Desires",
))
#client.event
async def on_message(message):
if message.content.startswith(prefix):
command = message.content[len(prefix):]
# Set welcome channel command
if command.startswith("setwelcomechannel"):
# Check if the user is an admin
if not message.author.guild_permissions.administrator:
await message.channel.send("You have to be an admin to set the welcome channel.")
return
# Set the welcome channel
global welcome_channel
welcome_channel = message.channel
await message.channel.send(f"Welcome channel set to {welcome_channel.name}.")
# Get welcome channel command
if command.startswith("getwelcomechannel"):
# Check if the welcome channel has been set
if welcome_channel is None:
await message.channel.send("Welcome channel is not set.")
else:
await message.channel.send(f"Welcome channel is set to {welcome_channel.name}.")
# Add your new commands here
if command.startswith("hello"):
await message.channel.send("Hii!")
if command.startswith("dead"):
await message.channel.send("latom!")
#client.event
async def on_member_join(member):
# Send the welcome message
if welcome_channel:
embed = discord.Embed(title="Welcome!", description=f"Ara ara! {member.mention}, welcome to {member.guild.name}\nHope you find Peace here!", color=0x8438e8)
embed.set_image(url= 'https://cdn.discordapp.com/attachments/998612463492812822/1063409897871511602/welcome.png')
await welcome_channel.send(embed=embed)
keep_alive()
TOKEN = os.environ.get("DISCORD_BOT_SECRET")
client. Run(TOKEN)
to run properly and to show an image in the presence.
"discord.client logging in using static token" error
That says INFO, not ERROR, so it's not an error. The actual error is the red lines underneath, which is caused by you using Replit to run the bot.
Replit uses the same IP address for every bot, so all Replit bots combined will cause Discord to ratelimit you. The only solution is to use an actual VPS instead of abusing Replit's platform to host bots. There's nothing you can do about it.

How do I send a message to a specific discord channel while in a task loop?

import discord
from discord.ext import commands, tasks
from discord_webhook import DiscordWebhook
client = discord.Client()
bot = commands.Bot(command_prefix="$")
#tasks.loop(seconds=15.0)
async def getAlert():
#do work here
channel = bot.get_channel(channel_id_as_int)
await channel.send("TESTING")
getAlert.start()
bot.run(token)
When I print "channel", I am getting "None" and the program crashes saying "AttributeError: 'NoneType' object has no attribute 'send' ".
My guess is that I am getting the channel before it is available, but I am unsure. Anybody know how I can get this to send a message to a specific channel?
Your bot cannot get the channel straight away, especially if it's not in the bot's cache. Instead, I would recommend to get the server id, make the bot get the server from the id, then get the channel from that server. Do view the revised code below.
#tasks.loop(seconds=15.0)
async def getAlert():
#do work here
guild = bot.get_guild(server_id_as_int)
channel = guild.get_channel(channel_id_as_int)
await channel.send("TESTING")
(Edit: Including answer from comments so others may refer to this)
You should also ensure that your getAlert.start() is in an on_ready() event, as the bot needs to start and enter discord before it would be able to access any guilds or channels.
#bot.event
async def on_ready():
getAlert.start()
print("Ready!")
Helpful links:
discord.ext.tasks.loop - discord.py docs
on_ready event - discord.py docs
bot.get_guild(id) - discord.py docs
guild.get_channel(id) - discord.py docs
"I can't get certain guild with discord.py" - Stackoverflow

Message Will Not Send To Channel w/ Discord.py

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")

Sending messages in discord.py #tasks.loop()

Goal:
I am simply trying to send a message to a discord channel from a #tasks.loop() without the need for a discord message variable from #client.event async def on_message. The discord bot is kept running in repl.it using uptime robot.
Method / Background:
A simple while True loop in will not work for the larger project I will be applying this principle to, as detailed by Karen's answer here. I am now using #tasks.loop() which Lovesh has quickly detailed here: (see Lovesh's work).
Problem:
I still get an error for using the most common method to send a message in discord using discord.py. The error has to have something to do with the await channel.send( ) method. Neither of the messages get sent in discord. Here is the error message.
Code:
from discord.ext import tasks, commands
import os
from keep_alive import keep_alive
import time
token = os.environ['goofyToken']
# Set Up Discord Client & Ready Function
client = discord.Client()
channel = client.get_channel(CHANNEL-ID)
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#tasks.loop(count=1)
async def myloop(word):
await channel.send(word)
#client.event
async def on_message(message):
msg = message.content
if msg.startswith('!'):
message_to_send = 'Hello World!'
await channel.send(message_to_send)
myloop.start(message_to_send)
keep_alive()
client.run(token)
Attempted Solutions:
A message can be sent from the on_message event using the syntax await message.channel.send('Hello World!). However, I just can't use this. The code is kept running online by uptimerobot, a free website which pings the repository on repl.it. When the robot pings the repository, the message variable is lost, so the loop would stop scanning my data in the larger project I am working on which is giving me this issue.
When using any client.get_* method the bot will try to grab the object from the cache, the channel global variable is defined before the bot actually runs (so the cache is empty). You should get the channel inside the loop function:
#tasks.loop(count=1)
async def myloop(word):
channel = client.get_channel(CHANNEL_ID)
await channel.send(word)

Cannot send message from console to discord

So I'm trying to send a message from the console to discord as if it were a /say command. Specifically I'm trying to input the channel id and a message, and get the bot to send it.
But when I run it no error appears, the bot goes online, and nothing is sent to the text channel
Here is my code:
import discord
from discord.ext.commands import Bot
TOKEN = open('token.txt').readline()
client = discord.Client()
bot = discord.ext.commands.Bot
channel_entry = input('ID: ')
msg_entry = input('Mensagem: ')
#client.event
async def send_channel_entry():
channel = client.get_channel(channel_entry)
await channel.send(msg_entry)
bot.run(TOKEN)
Of course nothing happens, because send_channel_entry is never called. Have you tried calling the command or activating it via Discord to see if it works?

Categories