discord.py - checking if channel id is correct - discord.py

In Discord.py I am currently coding a bot that basically acts as a system for one particular server, and isn't intended to be used as a public bot. But I still wanted to add commands in that makes it simple for administrators to configure the bot inside of Discord, all was well, until I ran into the issue of trying to check if a channel ID is actually correct or not when executing the command, but unfortunately I kept getting error after error after error.
#bot.command()
async def channel(ctx, type, id):
global channel_report
global channel_approve
if id != discord.TextChannel.id:
await ctx.send("Command terminated: bad id.")
return
if type == "report":
#code here
elif type == "approve":
#code here
What have I been missing? I have tried to approach this many different ways, even with methods such as get_message , but got nowhere, and as a newish programmer, but especially new to the Discord API in particular, I'm lost. Thanks for all of those who are dedicating their time to help me, computer coding is just one of them interests.

I'm assuming what you mean by "checking if a channel ID is correct" is that you want to make sure the given ID represents an actual channel that the bot can access. You can use bot.get_channel() to get a channel object from an ID. If the channel doesn't exist, it returns null. So you can just check if it is null.
channel = bot.get_channel(000000000000000000) # try to get a channel which doesn't exist
if channel is None: # will return true as invalid channel returns null
await ctx.send("Command terminated: bad id.")
return

Related

How to make a bot reaction to the end of the interaction?

I mean when it went long after the interaction has been created and the user again chooses a item from selectmenu and I want a bot to respond to the user
Code callbakck:
async def callback(iter:discord.Interaction):
if menu.values[0] == '1':
if iter.is_expired is True:
await iter.response.send_message(embed=discord.Embed(
title='Error!',
description='This interaction has expired. Please enter the appropriate command again so that it will work if necessary.',
color=0xff0000
))
else:
await iter.response.send_message(embed=discord.Embed(title='Інформація', color=settings['color'], description='You chose the category **Information**'))
That's the way I have a code not working
You can't respond to an interaction after it is expired, but you can still send a message to the channel assuming you have the proper permissions.
Also I'd highly recommend calling the Interaction variable interaction rather than iter since it is more readable.
eg.
await interaction.channel.send("interaction expired")
Also is_expired() is a method, so you may need to call it with parentheses.

Discord.py Bot Autodelete

Im new to python (i learned the basics at a school course),
and for the moment im trying to create simple bots for my discord server.
And for the moment, the bot i really want, is an autodelete bot so that i can say, (for example) delete every message in the ...Channel after 24h. because i really dont wanna do that manually.
I know there are a few good bots that do that,
but for example MEE6 wants me to buy Premium to use the funktion.The other reason why i dont want to use any finished bot is that i really want to understand and learn the code,
i watched many tutorials and tried to put the parts of the scripts that i understood together, but it did not work. I also didnt find a tutorial which explained it to me so that i understood, so now im here and hope that im going to understand it.
I hope there are some ppl to help me. :)
Thanks
-Yami.Code
#bot.event()
async def on_ready(ctx):
while requirement == 1:
await ctx.channel.purge
time.sleep(20)
#the Error is:
line 11, in <module>
#bot.event()
TypeError: event() missing 1 required positional argument: 'coro'
Process finished with exit code 1
You shouldn't call bot.event (remove the parenthesis),
time.sleep is a blocking call, use asyncio.sleep instead (What does "blocking" mean)
on_ready doens't take ctx as an argument, if you want to send a message to a channel you should get the channel object first, and then use the send method
You're missing a parenthesis in your channel.purge method...
import asyncio # if you haven't already
#bot.event
async def on_ready():
channel = bot.get_channel(channel_id) # replace `channel_id` with an actual channel ID
while requirement == 1:
await channel.purge(limit=x) # change `x` accordingly...
await asyncio.sleep(20)

discord.py save every message in specific channel (using channel id)

How can a python bot read every message that is sent in a certain channel or read every message that was sent in one using a command like $save 421345187663708161. Thanks in advance, havent been able to find the answer anywhere.
I made this in an on_message Function which scans the message content for "$save" on the beginning, then gets the channel per the given ID.
#client.event
async def on_message(message):
if message.content.startswith("$save"):
splittedcontent = message.content.split()
channel = client.get_channel(splittedcontent[1])
all_messages = channel.history()
What your job now is, is to understand this code, maybe inform about the things that are going on here (like channel.history) and implement this to your code (preferably also with some try/except cases).

Fetch the message sent by the bot before restarting the session

I know that I can get a message object using await ctx.fetch_message(mesId). Although If I send a message, and then start the bot's session (Restart the Client). The script cannot see the message. Is there any way to get rid of this problem?
Also, it's worth mentioning that I use discord.Bot type user not discord.Client
First of all there is no ctx.fetch_message ref
It should be ctx.channel.fetch_message Keep in mind you can get another channel by using await bot.get_channel(ID) and then fetch the message.
Your code should look like this:
# using another channel
channel = await bot.get_channel(123456)
message = await channel.fetch_message(123456)
# or using ctx
message = await ctx.channel.fetch_message(123456)
Docs

How do I get a bot to forward its DMs

So my bot DM's users and asks them questions, but I need to be able to see their response in a channel.
So far I have this:
#bot.event
async def on_message(message):
channel = bot.get_channel(642759168247463937)
await channel.send('message')
but it begins when any message is sent in any channel and it also responds to itself, causing an endless loop of spam.
I'm new to Discord.py so I honestly don't have a clue on how to resolve this issue.
My approach would be to check if the message came from DMs:
#bot.event
async def on_message(message):
if not message.guild:
return
channel = bot.get_channel(642759168247463937)
await channel.send('message')
This works because message.guild is None if the message was sent in DMs. This prevents the spam problem, since the message is not forwarded to the bot's DMs.
However, to avoid the spam in general, it is good practice to avoid responding to bots altogether, unless necessary. Luckily, User and Member objects have an attribute called bot that helps us here:
if message.author.bot:
return
Note that this is done automatically for commands using the ext.commands framework.

Resources