#discord-bots
1 messages · Page 310 of 1
have a look at the event section of the docs
section please
Looks like TOKEN was not defined
you would do await message.author.kick()
thank you
I need a help
I need a code which helps me check if a bot has sent me a message including "has uploaded a new video" on discord in a channel, and it has a usertoken not a bot token in it, like i am using my account's token for checking if anyone has uploaded a video so i get notified by myself.
that’s definitely not allowed
Hi, I'm making a PUT request to this endpoint /channels/{channel.id}/recipients/{user.id}
now the problem is that with the following headers:
{
"Authorization": "Bot XXXX",
"Content-Type": "application/json"
}
and with the following json encoded body:
{"access_token": "XXXX", "nick": "XXXX"}
I'm getting as response a 400 bad request code and an api error with the code 50035 and the following message "Cannot execute action on this channel type". Now the type of the channel_id is Group DM (3) indeed this endpoint /channels/{channel.id}/recipients/{user.id} returns a different code error:
50013 Missing Permissions
so now my question is, am i missing something?
Try this
token=os.environ['TOKEN']
client.run(token)```
because discord doesn’t permit you to automate your account
Oh lol i didnt even read the api docs sorry
can't seem to define TOKEN with that either unfortunately
What's the proper way to use a custom emoji in an embed with a bot?
that’s not very secure now is it
especially if he wants to make the source code open source
!d discord.Emoji
class discord.Emoji```
Represents a custom emoji.
Depending on the way this object was created, some of the attributes can have a value of `None`...
How do I get the string representation of them? I'm trying to use it in an embed description
Oh yoooo, I always skip over that part of the docs lol
Thanks very much
I feel dumb lol
main.py
import discord
from discord.ext import commands
from dotenv import load_dotenv
import os
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='.', intents=intents)
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
bot.load_extension(f'cogs.{filename[:-3]}')
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
print(f'Bot ID: {bot.user.id}')
bot.run(TOKEN)
cogs/ping.py
import discord
from discord.ext import commands
class Ping(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def ping(self, ctx):
await ctx.send('Pong!')
def setup(bot):
bot.add_cog(Ping(bot))
Warning when running
RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
bot.load_extension(f'cogs.{filename[:-3]}')
Error after commanding
2023-10-08 01:11:04 ERROR discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "ping" is not found
What is wrong?
I cannot install discord.py
Why do I need Microsoft Visual C++ to install discord.py for python?
you are using Python 3.12, which has been out for 1 Week. Libraries do not support it yet. Downgrade and use 3.11
load_extension is a coro
!d discord.ext.commands.Bot.load_extension
await load_extension(name, *, package=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Loads an extension.
An extension is a python module that contains commands, cogs, or listeners.
An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.
Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine).
Because Python libraries use a lot of C and C++ internally. It does not want Microsoft Visual C++ it wants MS Visual studio build tools, which the compiler tooling in order to compile C and C++. Visual studio just makes it really difficult to install just that though.
Therefore, you're also getting errors in your console that you're not sharing for some reason
Basically Discord.py depends on libraries which use C/C++ internally for speed
@night crater Thank you 
I know this is not really relevant to Python. But these Microsoft Visual C++ 32 and 64 bit is all I need for my OS?
maybe I cant remember which ones you need exactly
but I would probably not delete them
tbh I wouldn't be deleting them
They have such a minimal impact and have a possibility to break like basically everything
# Load Cogs
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
bot.load_extension(f'cogs.{filename[:-3]}')
using nextcord
command in 'cog' folder
how to make commands working if i put them in another folder in the cog folder.
for example: cogs/on_ready/Ready.py but not cogs/Ready.py
Hello everyone
I need help for make a command
I try to make a command use chatgpt for chatgpt provide a response to the prompt enter in the command
@bot.command()
async def ai(ctx, prompt):
if config["use_ai"] == "yes":
if config["ai_key"] == "":
print(f"{Fore.RED}[{datetime.datetime.now()}] [ERROR] No API key OpenAI found in config{Fore.RESET}")
print(f"{Fore.YELLOW}[{datetime.datetime.now()}] [TIPS] Set API key OpenAI in config.json, you will find it in the same folder{Fore.RESET}")
return
else:
openai.api_key = config["ai_key"]
prompt = prompt
response = openai.Completion.create(
model="text-davinci-003",
prompt=prompt,
max_tokens=300,
temperature=0.9
)
if response.choices[0].text:
await ctx.send(response.choices[0].text)
print(f"{Fore.GREEN}[{datetime.datetime.now()}] [AI] Response sent{Fore.RESET}")
else:
print(f"{Fore.RED}[{datetime.datetime.now()}] [ERROR] Empty response from OpenAI{Fore.RESET}")
else:
print(f"{Fore.RED}[{datetime.datetime.now()}] [ERROR] You have disabled the AI{Fore.RESET}")```
This is my code
When he answers, he answers totally nonsense
And when i put the same thing in on_message event i don't have this problem
your prompt argument currently only takes a singular word, by default, text commands takes a single word that is separated by space. so i would assume that's why it's a complete nonsense respond. you can change this so it takes the whole sentence by using consume rest in the parameter, ctx, *, prompt. you can read about that at dpy keyword only argument
Thanks for remember me that
I have miss since a long time i don't have make command with prefix
Can someone tell me how do I make it read a command found in 2 folders?
Cogs.
just read the second folder like you did with Cogs there?
./cogs/.../ ?
I want to open some
many for example
Not cogs/one folder/all the commands
glob.glob(pathname, *, root_dir=None, dir_fd=None, recursive=False, include_hidden=False)```
Return a possibly empty list of path names that match *pathname*, which must be a string containing a path specification. *pathname* can be either absolute (like `/usr/src/Python-1.5/Makefile`) or relative (like `../../Tools/*/*.gif`), and can contain shell-style wildcards. Broken symlinks are included in the results (as in the shell). Whether or not the results are sorted depends on the file system. If a file that satisfies conditions is removed or added during the call of this function, whether a path name for that file will be included is unspecified.
/cogs/**/*.py, then just convert the / to . when loading the extension, and exclude .py
:incoming_envelope: :ok_hand: applied timeout to @agile spade until <t:1696731065:f> (10 minutes) (reason: newlines spam - sent 110 newlines).
The <@&831776746206265384> have been alerted for review.
!unmute 741403526152061039
:incoming_envelope: :ok_hand: pardoned infraction timeout for @agile spade.
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
anyone mind Grading my discord bot code (made with nextcord, not discord.py) also im very new to coding in python (or coding in general) so i just wanted to know how i was doing https://paste.pythondiscord.com/RVTQ
PEP 8 is the official style guide for Python. It includes comprehensive guidelines for code formatting, variable naming, and making your code easy to read. Professional Python developers are usually required to follow the guidelines, and will often use code-linters like flake8 to verify that the code they're writing complies with the style guide.
More information:
• PEP 8 document
• Our PEP 8 song! :notes:
hm, ill have to look into that, thanks for letting me know tho!
So just generally,
- General pep8 and formatting
- See below
def getavg(list=list):not sure what you're doing here tbh- Here as well,
name=str, des=str, color=nextcord.Colour. Are you trying to typehint?=assigns a default value. You would use:for typehinting:def foo(string: str) - No need to return a tuple
return(embed) - You're naming your
commnads.Bot()instanceclientinstead ofbot - Using json as a db instead of a proper one, like sql
- Would fix this naming:
async def serverstats(ctx : Interaction) - This as well:
async def messagessent(ctx : Interaction, member : nextcord.User): - Bare
tryandexcept - I don't really see a point to
makeembedat all as you could just usenextcord.Embed() - You should only be using
Intents.all()if you really need all the intents, especially privileged ones
You could just use with open() and you won't need file.close() for
file = open('messagelengthavg.txt', 'r')
for messagelengthvalue in str(file.read()).split('-'):
lengths.append(int(messagelengthvalue))
file.close()
There's more stuff, but that's just surface-level imo
I gotta cook so I can't fully analyze it
you did this for literally every channel. wow
i would say there is a lack of documentation and lots of inefficient practices which will gradually make your code uglier and harder to maintain as you develop your bot, but at the same time you don't have too much code right now so you can easily make major changes, and trying to understand all the best practices at once is difficult if you aren't applying them to new features or projects
with that being said, i would suggest learning SQL and SQLite to store any data that changes often rather than in JSON/text files; it's fairly easy to learn and is a handy tool to know in general for other projects you might write
Hello
how to make app command like this
Yes just like this thankyou!
it keeps trying ask questions in channel or in DM.
making clutter.
it want it to cycle through the questions in the text area then once it has all the relevant information create an embed using it.
Or are you asking for the same thing ? lol
I thought you had seen my question in main discussion.. that would be one hell of a coincidence.
make the parameter typehinted as discord.Attachment i believe, or discord.File
Hi melvin I have a similar issue.
I am currently having issues with my Discord bot asking the questions either in the channel itself creating mess or sending a DM.
C+
thank you
I have seen other bots ask the relevant questions from within the text area after similar to the above screenshot.
Like a modal?
Just had a quick google, looks a bit different.
So for example where I've typed this I would put !newlisting.
In the message area it would then ask Name: with a box I could enter the name.
It would then move on to Age with another box...
and so on... sometimes it will have +1 when you want to add more than one reply.
you'd click the +1 to add another box to enter information into.
I've been searching Google images to see if I could find one.
the user above posted something similar.
without the drop file part.
Arghhh for some reason I keep either getting the bot to either ask the questions directly in the channel for everyone to see or in a personal DM.
and want it to ask like above.
Like this?
the country/weight part above.
Yeah so that's just a regular slash command
where I could type USA and 20kg into the fields.
It's not possible with a prefixed command
Okay cheers for the help.
👍
!d discord.Thread.edit
await edit(*, name=..., archived=..., locked=..., invitable=..., pinned=..., slowmode_delay=..., auto_archive_duration=..., applied_tags=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the thread.
Editing the thread requires [`Permissions.manage_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_threads). The thread creator can also edit `name`, `archived` or `auto_archive_duration`. Note that if the thread is locked then only those with [`Permissions.manage_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_threads) can unarchive a thread.
The thread must be unarchived to be edited.
Set the archived argument
how can I get the ID of a slash command?
Trying to get started with building a Discord bot, installed python, installed vitrual studio code.
When I go to install pip install discord I get the following error.
copying yarl\__init__.pyi -> build\lib.win-amd64-cpython-312\yarl
copying yarl\_quoting_c.pyi -> build\lib.win-amd64-cpython-312\yarl
copying yarl\_quoting_c.pyx -> build\lib.win-amd64-cpython-312\yarl
copying yarl\py.typed -> build\lib.win-amd64-cpython-312\yarl
running build_ext
building 'yarl._quoting_c' extension
error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for yarl
Failed to build aiohttp frozenlist multidict yarl
ERROR: Could not build wheels for aiohttp, frozenlist, multidict, yarl, which is required to install pyproject.toml-based projectss```
I've then visited the site and installed the visual studio build tools 2022. But still get the same error.
huh
!d discord.app_commands.AppCommand.id - you can fetch the object using the tree.fetch_command
The application command’s ID.
https://paste.pythondiscord.com/ID6Q
this is my code
can you check it and let me know how you do it
You set the archived argument:
await thread.edit(archived=True) # 🤷
Unless you're using a different lib, not discord.py
i am using nextcord.
yarl (aiohttp's dependency) isn't yet compatible with Python 3.12, so you need to wait until it does
Ahhh is there a workaround in the meantime ? installing an older version ?.
Yeah, you can downgrade Python for now
Sweet just the previous version is enough ? or further back.
Python 3.11 works fine
Thanking you :).
🐈
thank you!
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
catty catty .-.
Cogs
|
├─── Folder1
| |
| └─── cog1.py
|
├─── Folder2
| |
| └─── cog2.py
|
├─── Folder3
| |
| └─── cog3.py
|
└─── Folder4
|
└─── cog4.py
- Is it possible to do something like this? ^
- I want to make it automatically, without adding the path again and again.
- using
nextcord - I guess I have to do something with that:
# Load Cogs
for filename in os.listdir('./Cogs'):
if filename.endswith('.py'):
bot.load_extension(f'cogs.{filename[:-3]}')
making my first discord bot currently, any tips?
make one file for each command before u have a 5000 line file like me
this is what i do. discord.py tho but the concept is there
async def main():
async with bot:
[await bot.load_extension(f"commando.{file[:-3]}") for file in os.listdir("commando/") if file.endswith(".py")]
await bot.start(os.getenv('TOKEN'))
check dms rq
dont ask someone else to do this
its against the rule here
but its fine with me
That doesn't cover subfolders
but i dont have a subfolders so its fine :D
just add another for loop its going to be fine
You can use pathlib.Path("./cogs").glob("**/*.py") and it will list all .py files
Pathlib is actually pretty convenient, worth looking at
anyone here host their bot with the help of github student dev pack? i need help ;-; still cant fix the problem
well if you don't ask any questions, it's quite hard - we unfortunately ran out of crystal balls
someone tell me to get github student dev pack to get 1 year digital ocean to host my discord bot
but it needs a credit card and i dont have one
well, nothing we can help you with then - we won't give a credit card to some random users online
ask your parents or something
no like are there any alternative way of hosting a discord bot with the student dev pack
All services will require a credit card, so no
ok thanks
anyone know how to make a modal without using the / command
With what do you want one to be done
im pretty new to this but i think its called an embed message
sort of like a verify command
Yeah, then use slash commands and you can send a modal
does it stay?
Stay?
A modal gets sent once a user has an interaction
Which can be for example using a slash command or clicking a button
Then obviously it'll be gone once the user has filled the info and submitted it
That's an embed with a button
an example
oh
@slate swan im trying to recreate something that my friend made, hes trying to make me learn
from scratch
Well we'll help with issues you're facing, not code for you or similar
So if you have a concrete issue with your code, go ahead
👍
They denied my application cuz I am from Russia
What a politically biased company
They didn't even give me my free credit
I tried creating a ticket but no response
average DO
Hosting in Google Cloud platform cost any money?
It gives 300 credits and if u use them wisely u can host for around 3-6 months i think
But it also requires a credit card to claim the free credits
=.= they literally state that in the result?
Nah, the reason was "wrong billing info", but the thing is since I am russian I can't edit it
why cant u edit it
Because they banned users from Russia and Belarus from editing it
I had a beef with them
but how do i host a discord bot now 😭
went through all of that just to shit to the toilet because i dont have a cc
hey,is it possible to send a .txt file with smtplib in python?
yep
well it's not like it's github fault
Some abroad countries do that, so unless github is controlled by government it is
It's also possible with the email module
they are forced yk
iirc it depends where the society has the legal offices or the HQ
Hello everyone, I need help with this command which should create an Embed with several information on the server, but when I execute the command nothing happens
And I would also like to place it in slash commande but I can't do it either, thank you
Source Link : https://paste.pythondiscord.com/PITQ
!message_content
The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."
The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.
Privileged intents, such as message content, have to be explicitly enabled from the Discord Developer Portal in addition to being enabled in the code:
intents = discord.Intents.default() # create a default Intents instance
intents.message_content = True # enable message content intents
bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor
For more information on intents, see /tag intents. If prefix commands are still not working, see /tag on-message-event.
I'm trying to use CustomActivity on nextcord i'm trying to make it show emoji with the status but it doesn't work how can i fix?
https://paste.pythondiscord.com/VQNA
did you try printing out the emoji to see if it actually found the emoji?
What is wrong here? trying to learn how to create threads
it actually found the emoji but the status text only appears and no emoji
how did you check it found it
when i run the bot it showed no emoji but text status shown
so it didnt found the emoji?
the emoji is valid but for some reason it didnt show on status screen of the bot
It appears that discord's api limiting the emoji that's why it aint showing
i asked them about it on nextcord official server
How can I make an timer and if I respond to the interaction, interrupt this timer? Something similar to this example
Hey guys, is there a way to get username using A userid?
Look at the second example for https://discordpy.readthedocs.io/en/latest/ext/commands/api.html?highlight=wait#discord.ext.commands.Bot.wait_for
I'm new to interactions so I don't know how responding to interactions works
It's been a while
How can i make this embed look better
thanks
Does a user's Discord user ID ever change?
no
member = guild.fetch_member(user_id)
member.name
This will work if they are not in the server?
No, if you this want, use user = guild.fetch_user(user_id)
but I don't sure that possible get username
how can i create a thread in forum channel?
look at my screen shot. i used it and id deosnt work
you don't use tresc
and try delete auto_archive_dur, maybe you write wrong int
still not working
also, bot.get_channel(id)
where channel_id?
above this
Then I do not know how to help you
this is what it get:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'channel'
If the cache lookup there is top level, I'm assuming the cache is not yet populated at that point so there are no cache hits
so what should i do?
Move it into the command
still not working bro
Can you show us what you've got?
get_ returns None if it's not in cache so you'd have to use
x = bot.get_channel(...) or await bot.fetch_channel(...)
Would be nice if you could share errors and not just say "Not working"
.get_channel is not awaitable
already changed it. now i get this
get_channel just searches the bots cache, so it’s not a coro
What perms does the bot have in the server
admin
i can create thread in new created text channel, but when i try to do it in forum channel i get attribute error
Most likely ^
How should I go about dynamically creating inputs for modals? Since it's just based off the variables, how would I do it with a loop? I've tried [discord.ui.TextInput(label=second) for first, second in modal_item_text.items()], but they're not registering
So I see add_item, how would I use that?
Oop figured it out
I had to use add_item in the __init__
If I needed a user to send a day in a specific format, how would you guys recommend I do it? Just use wait_for, and show the format I want i.e. 17/9/2023 or is there a better way? Should I use select menus instead?
There is no native UI for selecting dates and times
Doing it in text is probably the best way, and regexing it
I know, and that's the issue tbh
Yeah, I was just trying to reduce chat clutter. I'll use wait_for then
@tree.command(guild= discord.Object(id=id_do_servidor), name="efetivo", description="Atualizar Efetivo.")
async def setup(interaction: discord.integrations):
try:
role_id = int(#id do cargo)
role = discord.utils.get(interaction.guild.roles, id=role_id)
if role is None:
await interaction.response.send_message(f"Função com o ID '{role_id}' não encontrada.")
return
members_with_role = [member.mention for member in interaction.guild.members if role_id in [r.id for r in member.roles]]
if members_with_role:
members_list = " ".join(members_with_role)
await interaction.response.send_message(f"{role.mencion}\n>>> {members_list}")
else:
await interaction.response.send_message(f"Nenhum membro possui a função {role.mention} no servidor.")
except ValueError:
await interaction.response.send_message("ID de função inválido. Por favor, forneça um ID de função válido.")
``` It's showing that there's no one with that role, but my friend and I have it. Where could I have gone wrong?
Do you have member intents?
?
What about the question do you not understand
I think so, because it was working before.
import discord
from discord import app_commands
from discord.ext import commands
from decouple import config
Permissions for the bot?
No, intents lol
I'm sorry, I don't understand anything because I'm using Google Translate, I don't know English.
"I don't have that line, should I show you the entire code?
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
I understand, thank you.
channel = client.get_channel(ID)
await channel.send('stuff')
when i run this code it says
AttributeError: 'NoneType' object has no attribute 'send' why?
cus i've done the same thing before
and it worked
get_channel returns None when the channel isn’t in the bots cache
Consider using
!d discord.Client.fetch_channel
await fetch_channel(channel_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel), [`abc.PrivateChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.PrivateChannel), or [`Thread`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Thread) with the specified ID.
Note
This method is an API call. For general usage, consider [`get_channel()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.get_channel) instead.
New in version 1.2.
Changed in version 2.0: `channel_id` parameter is now positional-only.
so channel = await client.fetch_channel(id)
Try it and see
i'd use a parser
from dateutils
!d dateutil.parser.parse
parser.parse(parserinfo=None, **kwargs)```
Parse a string in one of the supported formats, using the `parserinfo` parameters.
| Parameters: | • **timestr** – A string containing a date/time stamp.
• **parserinfo** – A [`parserinfo`](https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.parserinfo) object containing parameters for the parser. If `None`, the default arguments to the [`parserinfo`](https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.parserinfo) constructor are used.
|
The `**kwargs` parameter takes the following keyword arguments:
this ^
I'll look into it
I was more looking on how I should do it though
Have 3 select menus, 1 for year, one for month, one for day, or just use wait_for with a given example (or the parser you gave)
Or if there's any options I'm missing
The parser will be useful though, help minimize user error
The problem with this is the day. Select menus can only show 25 days and there are more than 25 days in a month
So it's not an ideal interface
Same thing with year, obviously
Well for year it'll only be like 3, but yeah, I get your point
That's my whole position, there aren't any good formats for this
Another option is slash command with choice for month, and int inputs for day and year
Actually, how many buttons can you attach to a message?
25
Nah wouldn't work as well
A native interface for selecting datetimes would be really nice
Unfortunately the SelectOption is dependent on the input from the slash commands previous options
Yeah, like a small calender or something
They're already pretty close tbh
Literally just copy paste this as a new slash command option type
Only if it was available to bots 😭
Discord needs to put more love into their bot devs
Bots are literally the backbone of Discord, and for 5 years they we're really the only thing that prevent servers from being constantly raided
And nuked etc
It's already been a few months since it was data mined that datetime options are under work and would come
People got hyped, and now still nothing
Datamine and netscanning are quite annoying
hey
i need some help
@commands.command(aliases=['r','grole'])
@commands.has_permissions(manage_roles=True)
async def role(self,ctx, member: discord.Member, role_name: discord.Role):
await member.add_roles(role_name)
embed = discord.Embed(description = f'{emoji.check} **{role_name}** has been `given` to {member.mention}', color=color.color)
await ctx.reply(embed=embed,mention_author=False)
gives role fine but if the role is 2 words it dont
@final iron
, *, role_name: discord.Role
put a *
ty i shouulve knew
How do you get which ip should be scanned?
I don't, I am being scanned
I suspect that's because of noip
wow... something i needed my whole time.. 😮
Yes, there are some libs I too wish I learned earlier
Like pendulum, pathlib and durations-nlp
Is it possible to send epheral messages not with slash commands?
Yes but this only works with InteractionResponse
So you have to create a button view.
Nah not even buttons
Unfortunately i dont know any other ways to do so
No you can't
Alr
You could make a wrap-around, you could create a button view, but this gets triggered "Interacted" by a command (the command you want to get an epheral from).
an from that InteractionResponse that gets triggered by the command, you can send the epheral
Its alr
yo just wanted to ask if we can access the list of banned members with our bot and revoke the ban?
nvm found it
<@member_id> or if you have the Member object you can use its .mention property
!d discord.Member.mention
property mention```
Returns a string that allows you to mention the member.
i dont see the <>
^
its inside the string
discord/member.py lines 582 to 585
@property
def mention(self) -> str:
""":class:`str`: Returns a string that allows you to mention the member."""
return f'<@{self._user.id}>'```
yeah for whatever reason you removing the messages xd?
average people asking for help but don't want to show they're newbies to everyone
but be a big
saying they fixed the issue themselves

@tree.command(guild=discord.Object(id=id_do_servidor), name="efetivo", description="Atualizar Efetivo.")
async def setup(interaction: discord.interactions):
try:
intents = discord.Intents.default()
intents.members = True
intents.guilds = True
role_id = int(1160986660218089485)
role = discord.utils.get(interaction.guild.roles, id=role_id)
if role is None:
await interaction.response.send_message(f"Função com o ID '{role_id}' não encontrada.")
return
members_with_role = [member.mention for member in interaction.guild.members if role_id in [r.id for r in member.roles]]
if members_with_role:
members_list = "\n".join(members_with_role)
await interaction.response.send_message(f"{role.mention}\n>>> {members_list}")
else:
await interaction.response.send_message(f"Nenhum membro possui a função {role.mention} no servidor.")
except ValueError:
await interaction.response.send_message("ID de função inválido. Por favor, forneça um ID de função válido.")
``` It's only fetching the bot's roles and listing only them, not those of other members.
!e
data = [1,2,3,-2,5,0,7]
def selection_sort(list):
n = len(list)
for i in range (n):
for j in range(i+1, n):
if list[j] > list[j+1]:
list[j], list[j+1] = list[j+1], list[j]
return list
a = selection_sort(data)
print (a)
@weary pendant :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 9, in <module>
003 | a = selection_sort(data)
004 | ^^^^^^^^^^^^^^^^^^^^
005 | File "/home/main.py", line 6, in selection_sort
006 | if list[j] > list[j+1]:
007 | ~~~~^^^^^
008 | IndexError: list index out of range
#bot-commands
Do you have member intents?
Can discord bots be programed with python 3.12?
Is there any quick way to tell what latest version of python can be used to develop discrod bots?
3.11 is the latest version available rn, you can tell what python version is supported by looking at the pypi page or the pyproject.toml of the library
Thanks
if you're going by the docs or pypi, 3.11 is not listed as a supported version
it is on pypi
you sure? maybe i missed it, where?
in the classifiers section, you can even check it from the source code https://github.com/Rapptz/discord.py/blob/master/setup.py#L95-L98
setup.py lines 95 to 98
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Programming Language :: Python :: 3.11',```
pyproject.toml lines 26 to 29
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",```
yes
The intents are active within Discord Developer, and I've pulled them through the code, but it's not working; it only pulls the bot itself.
It only retrieves the roles of the bot itself.
Show how you enabled them
@final iron
No, in your code
Only this part of the code that I pulled the intents.
When you enable intents, you need to pass them into your bot constructor
You’re not doing that in the code you showed
How do I pass them?
!intents
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
!d discord.Client
class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.
async with x Asynchronously initialises the client and automatically cleans up.
New in version 2.0.
A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client).
intents arg
Does anyone have a list of all @discord.Clinet.event list?
For discord.py
!d discord.Client.event
class client(discord.Client):
def __init__(self):
super().__init__(intents=discord.Intents.default())
self.synced = False
async def setup_hook(self) -> None:
self.add_view(DropdownView())
async def on_ready(self):
await self.wait_until_ready()
if not self.synced:
await tree.sync(guild=discord.Object(id=id_do_servidor))
self.synced = True
print(f"Entramos como {self.user}.")
``` But am I not already passing it like this? @final iron ```super().__init__(intents=discord.Intents.default())```
Blud is mixing 2 tutorials
No, default is only non privileged intents
You need members to be enabled
!d discord.Client.event - their docs does
@event```
A decorator that registers an event to listen to.
You can find more info about the events on the [documentation below](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events).
The events must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine), if not, [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) is raised.
Example
```py
@client.event
async def on_ready():
print('Ready!')
```...
Why sync in on_ready when you're already using setup_hook 🫠
Hmm
Traceback (most recent call last):
File "/home/runner/scare1/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/scare1/cogs/lookup.py", line 20, in roblox
followers=str(requests.get(f"https://friends.roblox.com/v1/users/{id}/followers/count").json()['count'])
KeyError: 'count'
The above exception was the direct cause of the following exception:
traceback
followers=str(requests.get(f"https://friends.roblox.com/v1/users/{id}/followers/count").json()['count'])
friends=str(requests.get(f"https://friends.roblox.com/v1/users/{id}/friends/count").json()['count'])
following=str(requests.get(f"https://friends.roblox.com/v1/users/{id}/followings/count").json()['count'])
@final iron
it's not a discord-related issue, but you probably wanna use a different variable name than id, since it shadows a built-in function
check the id is correct and print the full json data to see what's going on I guess
and consider using aiohttp in place of requests since discord bots are asynchronous applications
yeah i fixxed it
so im having problems with my discord dashboard for my bot i always get the invalid redirect_uri oauth2 error can anyone help me?
this is my code and the uri i have on discord for the app is http://localhost:5000/authorized
from flask import *
from debuger import Debugger
from flask import Flask, redirect, request, url_for, session
from flask_oauthlib.client import OAuth
oauth = OAuth(app)
discord = oauth.remote_app(
'discord',
consumer_key='my app id ',
consumer_secret='my app secret',
request_token_params={'scope': 'identify'},
base_url='https://discord.com/api/',
request_token_url=None,
access_token_method='POST',
access_token_url='https://discord.com/api/oauth2/token',
authorize_url='https://discord.com/api/oauth2/authorize',
)
debugger = Debugger()
@app.route('/')
def index():
if 'discord_token' in session:
return 'Logged in as: ' + session['discord_user']['username']
return 'Not logged in.'
@app.route('/login')
def login():
return discord.authorize(callback=url_for('authorized', _external=True))
@app.route('/logout')
def logout():
session.pop('discord_token', None)
session.pop('discord_user', None)
return redirect(url_for('index'))
@app.route('/authorized')
def authorized():
print("Inside the authorized function")
response = discord.authorized_response()
if response is None or response.get('access_token') is None:
return 'Access denied: reason={} error={}'.format(
request.args['error_reason'],
request.args['error_description']
)
session['discord_token'] = (response['access_token'], '')
user_info = discord.get('users/@me').data
session['discord_user'] = user_info
return 'Logged in as: ' + user_info['username']
@discord.tokengetter
def get_discord_oauth_token():
return session.get('discord_token')
Hi
I was progress on a fuction in bot that could recieve images + text from api
This is the result (unfinished)
I was curious how can i let the text (brinewater springs) in that text box (text change every 2 hour) is it possible let it in box everytime?
!e dm
@fiery girder :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | dm
004 | NameError: name 'dm' is not defined
!e discord.dm
@fiery girder :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | discord.dm
004 | ^^^^^^^
005 | NameError: name 'discord' is not defined
!e
try:
import discord
print("success")
except Exception: print("epic fail")
@knotty agate :white_check_mark: Your 3.12 eval job has completed with return code 0.
epic fail
!d discord.DMChannel
class discord.DMChannel```
Represents a Discord direct message channel.
x == y Checks if two channels are equal.
x != y Checks if two channels are not equal.
hash(x) Returns the channel’s hash.
str(x) Returns a string representation of the channel
Where and how should I host my discord bot?
On ur pc?
no ofc not, im not gonna leave it on 24/7
!hosting
Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.
See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.
You may also use #965291480992321536 to discuss different discord bot hosting options.
kk thx
I dont wanna host it on a VPS tho, Im poor
Welp then you can use some spare device or pc
something like railway or render maybe?
Can I use netlify? Will it work?
You can try I'm not sure
Like the replit method but on netlify
I'd rather spend some money than going for free
And I don't think 2-5$ per month is too much
I would spend some bucks if it wasnt for this:
¯_(ツ)_/¯
Lol
i need someone for testing my bot can anyone volunteer?
sure
ok ill send invite
aight
u got nitro tho. how you can’t afford it
class TicketMain_One(nc.ui.View):
def __init__(self, header, textbox, button_one):
super().__init__()
self.header = header
self.textbox = textbox
self.button_one = button_one
print("--------")
print(button_one)
print(self.button_one)
print("---------")
self.b_one = nc.ui.button(style=nc.ButtonStyle.blurple, label=button_one)
#@nc.ui.button(style=nc.ButtonStyle.blurple, label=button_one)
async def b_one(self, button: nc.ui.Button, inter: nc.Interaction):
inter.response.send_message("HI")```
He is not sending the button
Well you have a hashtag in front of the decorator, commenting it out
Also, interaction should be first unless nextcord is different
Bit i need button_one as lavel
Bit?
What?
I never mentioned button_one
Your button decorator is commented out
how do i test discord bot?
some commands need to communicate with discord so mainly how do i test that
like unit tests for discord bots?
yea
tbh not really any way since to test u would need to automate the discord process too from a browser page generally this part is not too hard but then invoking commands would make it self botting
u can mostly only automate the non discord parts as testing
I think it would be nice of dpy and forks if they implemented sort of emulation of discord to test bots on
Since you mostly need to test messages that are sent back and actions the bot takes
Imagine like
@command()
async def hi(ctx):
await ctx.send(f"Hi, {ctx.author.mention}!")
async def test_hi():
ctx = VirtualContext(author=discord.Object(69420))
await hi(ctx)
ctx.assert_last_message(content="Hi, @onyx raven")```
so no emulation exist?
no
Not yet ☺️
time to make one 💪
Sure after my fellow team of bobux developers finally gets to v1.2
i didnt get it
You wouldn't ☺️
i mean emulation would be a huge project given discord api that would be a whole project as in of itself
u would probably have to spin up instances of ur own discord api and event systems to emulate it
It would indeed be huge but API instances nah
As I see it you just replace objects that interact discord API with virtual objects or test objects that interact with themselves
That's most likely not going to be 100% accurate but better than nothing
how is it going to be actually emulating. whats it going to look like
if i am right when all requests send to discord will redirected to ur program then youu need to make it so that ur program's resposne will be similar of discord
that made no sense at all
what i saw
- some actions in discords are irreversilble like banning people or something (sure you can unban the user but user need to rejoin back so breaking automatic testing?)
- ratelimiting (i am not sure how much this will effect)
i am beginner so an experienced person will have more and better points
ratelimiting wont be relevant if you're just testing
i can somewhat see the first point though
i feel like the amount of effort for the implementation into the library will be huge
but the pay off wont be
you wouldnt really need that to test most of the features bots have these days
!d discord.Client
class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.
async with x Asynchronously initialises the client and automatically cleans up.
New in version 2.0.
A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client).
what command is for creating channels??
!d discord.Guild.create_text_channel
await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel) for the guild.
Note that you must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels) to create the channel.
The `overwrites` parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict) of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite) as the value.
Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit) will be required to update the position of the channel in the channel list...
thanks
np
can i set a variable for a await command?
await bot.get_guild(payload.guild_id).get_category(appeal_category).create_text_channel(f"Banned-Appeal-{payload.user_id}")
like this i just put a var so maybe i can store the text channel?
according to the docs, yes
oh ok
discord.py cool
i saw the message
why not pycord (i am curious)
??
oh i mean why did this server choose discord.py over pycord 🤦
its made by people not discord
which one?
they dont have access to the things needed to make it
yes they do
this is made by discord
the API docs the API the developer portal
all made by discord
what does it do? (i mean feature you are aiming to add)
okay
this code is a mess i wish there was a prettier for python lol
there are many
for example??
black, autopep8
ruff
black
black?
yea
or for example for sorting imports isort
which is best?
i use black
what were you expecting
i am lazy af i aint gonna manually do things thats not important
you can try black then
ok lemme try that
and chooose the default formatter too
i belive you need to install extensions for Black or Ruff
as they say
"once you go black, you never go back"
black is extension
in vs code marketplace
and also available in pip
does pycord have something that discord.py doesnt have
i dont know so asking
as i said black is better then ruff
is there a shortcrut option to use a command in powershell without opening it in vscode
pip install black
black test.py
ik the command dude
i just wanna press a button and it automattically format the code
what is the command for changing channel name
!d discord.TextChannel.edit
await edit(*, reason=None, **options)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the channel.
You must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels) to do this.
Changed in version 1.3: The `overwrites` keyword-only parameter was added.
Changed in version 1.4: The `type` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead...
iirc in vscode there should be a combination of keys for that
^ install the black formatter extension and alt+shift+f to format
i saw that
roleprice = role1price
if role in interaction.user.roles:
await interaction.response.send_message("** لا يمكنك شراء رول تمتلكها بالفعل**",ephemeral=True)
else:
tax = ceil(roleprice / 0.95)
embed = discord.Embed(title=role1.name, description=f"""قم بتحويل {roleprice} ل {bank.mention}
What is this
?
can you share full code using pastebin?
my command isnt getting registered in bot section plz help and bot comes online
anyone plz help
@glossy ruin
doesnt work tells us nothing
Remember to:
• Ask your Python question, not if you can ask or if there's an expert who can help.
• Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
• Explain what you expect to happen and what actually happens.
ok
anyone??
or anyone plz help me here: https://discord.com/channels/267624335836053506/1161346076410921081
!pep 8
mb, wrong channel
hey newbie use #bot-commands
thanks :3

bot.command() doesn't work
• Ask your Python question, not if you can ask or if there's an expert who can help.
• Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
• Explain what you expect to happen and what actually happens.
I don't have err messages
yes same it also doesnt work for me bot comes online but commands dont get registered 😭
show full code
I can't send here its big
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
I'll send to dm
import discord
from discord.ext import commands
import lists
engel_ac = False
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix=".", intents=intents)
@bot.event
async def on_ready():
print("Bot hazır!")
@bot.event
async def on_message(message):
if message.author == bot.user:
return
for x in lists.kufurler:
if message.content.lower().startswith(x) or x in message.content.lower():
await message.delete()
print(f'\nKüfürlü mesaj: {message.content} \nKullanıcı: {message.author} \n')
await message.channel.send(f'{message.author.mention} küfür etmek yasak!')
@bot.command()
async def qwe(ctx):
global engel_ac
engel_ac = True
await ctx.send('Küfür engeli açtım, şimdi küfür etmeyi deneyin!')
@bot.command()
async def ping(ctx):
await ctx.send('pong')
!intents
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
!tag on_message
bro srsly?
if thats full code you dont have bot.run but i belive you just deleted it
bring danny bot here
!on_message
Registering the on_message event with @bot.event will override the default behavior of the event. This may cause prefix commands to stop working, because they rely on the default on_message event handler.
Instead, use @bot.listen to add a listener. Listeners get added alongside the default on_message handler which allows you to have multiple handlers for the same event. This means prefix commands can still be invoked as usual. Here's an example:
@bot.listen()
async def on_message(message):
... # do stuff here
# Or...
@bot.listen('on_message')
async def message_listener(message):
... # do stuff here
You can also tell discord.py to process the message for commands as usual at the end of the on_message handler with bot.process_commands(). However, this method isn't recommended as it does not allow you to add multiple on_message handlers.
If your prefix commands are still not working, it may be because you haven't enabled the message_content intent. See /tag message_content for more info.
yes deleted
he forgor process_commands()
what is process_commands()
replace ```py
@bot.event
``` with @bot.listen() above on_message
ok
tysm!
@shrewd fjord still commands not registered
provide code
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
@bot.hybrid_command(name="whitelist", description="Whitelist a user", with_app_command=True)
@commands.has_permissions(administrator=True)
async def whitelist(ctx, name: str):
whitelist = addwhitelist(name) # You may need to implement this function
await ctx.send(content=f"Added {name} to Whitelist: {whitelist}")
down lurking bad
this is just 1 code example from bot
@shrewd fjord
oh man, whatever sync your commands in setup_hook using await bot.tree.sync()
bot.tree.sync()
sob
await sync(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Syncs the application commands to Discord.
This also runs the translator to get the translated strings necessary for feeding back into Discord.
This must be called for the application commands to show up.
sob
i have created my own discord AI bot. I dont want anyone from my server to Dm my bot but they can acces it only from my server is there any settings in discord or something like that.
@shrewd fjord @slate swan ayooo
tyyyyyyyyyyyyyyyyssssssssssmmmmmmmmmm
worked lol
!d discord.ext.commands.guild_only
@discord.ext.commands.guild_only()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command.
This check raises a special exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage) that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure).
If used on hybrid commands, this will be equivalent to the [`discord.app_commands.guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only) decorator. In an unsupported context, such as a subcommand, this will still fallback to applying the check.
@gray grotto ^
help !
thats the help
is am in wrong channel ?
no thats the decorator you need to add above command to be only available in guilds
oo thanks
@slate swan when I make kufur_engel_ac the engel_ac be True but
this code not work
if engel_ac:
for x in lists.kufurler:
if message.content.lower().startswith(x) or x in message.content.lower():
await message.delete()
print(f'\nKüfürlü mesaj: {message.content} \nKullanıcı: {message.author} \n')
await message.channel.send(f'{message.author.mention} küfür etmek yasak!')
sry for ping
(solved, I forgot to delete qwe argument)
on_message takes only message argument not others
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.messages) to be enabled.
Warning
Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot) does not have this problem.
hi if someone could help me create a twitter bot i would really appreciate that
hello, I'm trying to work on logs channel. I got to the point of edit messages and I get an error th i dont know ho to work with (The error: NameError: name 'message' is not defined)
What can i do?
@bot.event
async def on_message_edit(message_before, message_after):
embed = discord.Embed(title = f"{message_before.author.name} has edited a message (user id: {message_before.author.id})", description = f"{message.content}")
embed.add_field(name = "Before Message", value = f"{message_before.content}", inline = False)
embed.add_field(name = "Aftr Message", value = f"{message_after.content}", inline = False)
embed.set_footer(text ="This bot was made by _mr3x. ")
channel = bot.get_channel(logs channel)
await channel.send(embed = embed)
well you're trying to use message.content but message is not defined, it should be message_before.content (if you want to show the content before the message edit - AKA the old content)
let me try
Thank you!
you're welcome
def __init__(self, client):
self.client = client
@bot.event()
async def on_guild_channel_create(self, channel):
if "ticket" not in channel.name:
return
class ButtonView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.add_item(discord.ui.Button(label="Placeholder 1", style=discord.ButtonStyle.grey, custom_id="1"))
self.add_item(discord.ui.Button(label="Placeholder 2", style=discord.ButtonStyle.grey, custom_id="2"))
self.add_item(discord.ui.Button(label="Placeholder 3", style=discord.ButtonStyle.grey, custom_id="3"))
self.add_item(discord.ui.Button(label="Placeholder 4", style=discord.ButtonStyle.grey, custom_id="4"))
self.add_item(discord.ui.Button(label="Placeholder 5", style=discord.ButtonStyle.grey, custom_id="5"))
self.add_item(discord.ui.Button(label="Placeholder 6", style=discord.ButtonStyle.grey, custom_id="6"))
self.add_item(discord.ui.Button(label="Placeholder 7", style=discord.ButtonStyle.grey, custom_id="7"))
self.add_item(discord.ui.Button(label="Placeholder 8", style=discord.ButtonStyle.grey, custom_id="8"))
emb = discord.Embed(title="Placeholder", description="Placeholder", colour=discord.Colour.light_grey())
await channel.send(embed=emb, view=ButtonView())
return```
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\Recoding Soul\main.py", line 1670, in <module>
class ButtonCommands(commands.Cog):
File "C:\Users\Administrator\Desktop\Recoding Soul\main.py", line 1675, in ButtonCommands
@bot.event()
^^^^^^^^^^^
TypeError: Client.event() missing 1 required positional argument: 'coro'
Question, is having a live ping command, i.e, the bot ping keeps updating after every X amount of seconds good to have, for debugging, or network errors, or just something usefull a whole
No imo
Just setup logging and it'll capture any useful debugging information
can i dm u?
Just ask your question, you're wasting everyone's time; and asking for random DMs is being weird
sorry..
And other people may also find the answer useful for them if you ask here, which is a bit the purpose
ur righ
Traceback (most recent call last):
File "/home/runner/stakeus/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/stakeus/main.py", line 49, in tt
Json = json.loads('{' + response.text.split('crossorigin="anonymous">{')[1].split('</script><script')[0])
IndexError: list index out of range
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/stakeus/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/stakeus/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/runner/stakeus/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/core.py", line 244, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: list index out of range
this is the eror
I doubt TikTok allows scraping
Yep they don't
In any event, you must not use the Platform to extract any data or content from the Platform using any automated system or software that is not provided by TikTok or approved in writing by TikTok; or
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
ive got a question
can u help me with welcome messgage config for every server
Yes
thanks
When checking if something is equal to one thing or another, you might think that this is possible:
# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
im starting with slash commands today......wut all shud i know?
Python: decorators, coroutines, classes, enums, typing.Literal
Discord.py: the interaction api
can u pls gimme a sample code fomme to kickstart......kinda confused abt which to go wid
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
Only get into discord bots if you have at least intermediate level understanding of python
Otherwise start with something simpler
had used up until 1.7.3 was stable n thn i stopped coz exams.........now m clueless abt this
hell i evn had music commands up n running....good ol days
Welp dpy went some changes from v2.0+ so you will need to get updated with it
yo guys how to fix this error
@bot.command()
async def mute(ctx, user:discord.Member, time, reason):
guild = ctx.guild
muteRole = discord.utils.get(guild.roles, name="Muted")
if not muteRole:
muteRole = await guild.create_role(name="Muted")
for channel in guild.channels:
await channel.set_permissions(muteRole, speak=False, send_messages=False, read_message_history=True, read_messages=True)
await user.add_roles(muteRole, reason=reason)
await user.send(f'{reason} sebebi ile {time} boyunca mutelendin')
while time > 0:
t.sleep(1)
time -= 1
if time == 0:
await user.remove_roles(muteRole)
break
some changes u say n i see it uprooted
ahh thenks fo dis
You are comparing time which is an str with an int
how to fix it
You will need to convert the time to either int or float depending on your use case
ok wait
thanks worked
I have a question how to do hours and days and minutes?
You will need to check the time string for the respective words and then strip the digit from it and do calculation on it to convert it seconds
ok ty
A key part of the Python philosophy is to ask for forgiveness, not permission. This means that it's okay to write code that may produce an error, as long as you specify how that error should be handled. Code written this way is readable and resilient.
try:
number = int(user_input)
except ValueError:
print("failed to convert user_input to a number. setting number to 0.")
number = 0
You should always specify the exception type if it is possible to do so, and your try block should be as short as possible. Attempting to handle broad categories of unexpected exceptions can silently hide serious problems.
try:
number = int(user_input)
item = some_list[number]
except:
print("An exception was raised, but we have no idea if it was a ValueError or an IndexError.")
For more information about exception handling, see the official Python docs, or watch Corey Schafer's video on exception handling.
How do I get channel ID by mentioning in like for example I use the command -log_channel #welcome , In my json file it dumps as <#channel_id>
How do I make it dump as channel_id
Any1?
The channel ID.
I dont understand
show code
What I wrote:
@client.command()
@commands.has_permissions(administrator=True)
async def log_channel(ctx, channel):
server_id = str(ctx.guild.id)
server_settings[server_id] = channel
with open('logs.json', 'w') as logs_file:
json.dump(server_settings, logs_file)
await ctx.send(f"Log channel updated to: {channel} for this server.")```
typehint it
wa-
channel: discord.TextChannel
o alr
then
instead of ... = channel
use
... = channel.id
Ooo
@shrewd fjord
@client.command()
async def credits(ctx):
creation = 1696967769
with open("logs.json", "r") as f:
logs = json.load(f)
logs = logs[str(ctx.guild.id)]
channel = logs
await channel.send("Test")
await ctx.send(f"Bot was created on <t:{creation}>")```
Give this error:
```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'int' object has no attribute 'send'```
The other command worked
you are now dumping id
!d discord.Guild.get_channel
get_channel(channel_id, /)```
Returns a channel with the given ID.
Note
This does *not* search for threads.
Changed in version 2.0: `channel_id` parameter is now positional-only.
so
channel = ctx.guild.get_channel(logs)
python bot.py
Traceback (most recent call last):
File "C:\Users\frrrrnamexdbot.py", line 3, in <module>
from discord_interactions import SlashCommand, SlashContext
ModuleNotFoundError: No module named 'discord_interactions'
bro holy shit iim not able to fix this shit im doing all stuff of fixing from 1hr help me plz 😭
@shrewd fjord
help plz anyone
discord.py supports application commands already, you dont need a third party library to use application command
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
follow this gist, if u want to use slash cmd using dpy
hey im trynig to solve a problem on my telegram bot where should i ask
my telegram bot script*
create a post here
Can someone help me how to make discord bot
ok
Can someone help me how to make discord bot
Do you have a specific question?
Bro I want make bot for my discord server but I don’t know how to make one
I want to create my own Telegram bot. I am not an expert in programming. This is my first project and I am facing this error
C:\Users\dlç\Desktop\TelegramBot>python telegram_bot.py
Traceback (most recent call last):
File "C:\Users\dlç\Desktop\TelegramBot\telegram_bot.py", line 14, in <module>
updater = Updater(token=TOKEN, bot=bot, workers=4)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Updater.init() got an unexpected keyword argument 'token'
this is the script i have :
import telegram
from telegram.ext import Updater, CommandHandler, MessageHandler, filters
import queue # Import the queue module
# Replace "YOUR_API_TOKEN" with your actual API token
TOKEN = "API"
CHANNEL_USERNAME = "@username" # Replace with your channel username
bot = telegram.Bot(token=TOKEN)
update_queue = queue.Queue() # Initialize the update queue
# Initialize the Updater class with both bot and update_queue
arguments
updater = Updater(token=TOKEN, bot=bot, workers=4)
dispatcher = updater.dispatcher
# Dictionary to store groups of images with their chat IDs
image_groups = {}
def store_images(update, context):
chat_id = update.message.chat_id
# Get the list of photos sent by the user
photos = update.message.photo
# Store the images in the dictionary with the chat ID as the key
if chat_id not in image_groups:
image_groups[chat_id] = []
image_groups[chat_id].append(photos[-1].file_id)
update.message.reply_text("Group of images stored successfully!")
Register the handler for storing images
dispatcher.add_handler(MessageHandler(filters.photo, store_images))
def send_next_group(context: CallbackContext):
for chat_id, image_group in image_groups.items():
# If there are images to send
if image_group:
# Get the oldest group of images for this chat
group_to_send = image_group.pop(0)
# Send the group of images to the channel
bot.send_media_group(chat_id=CHANNEL_USERNAME, media=
[telegram.InputMediaPhoto(media=image_id) for image_id in group_to_send])
# Schedule sending the next group of images at the beginning of every
hour from 9am to 8pm in Morocco time
morocco_tz = pytz.timezone('Africa/Casablanca')
morocco_schedule =
schedule.every().hour.at(":00").do(send_next_group)
morocco_schedule.run_every(1).day.at("08:00").do(lambda:
schedule.clear(morocco_schedule))
# Start the bot
updater.start_polling()
updater.idle()
is it not alwed ??
I don’t know
I think it's fine. It's just using the telegram API
the script is fine ??
this one is not working i made it using chat gpt but chat is not updated so now im looking for help
yes
Both are, use what you know
Both are fine. Though discord.py is a bit more advanced IMO
You'll need more knowledge than that to start making a bot with discord.py
Ok
class TicketMain_One(nc.ui.View):
def __init__(self, header, textbox, button_one):
super().__init__()
self.header = header
self.textbox = textbox
self.button_one = button_one
print("--------")
print(button_one)
print(self.button_one)
print("---------")
self.b_one = nc.ui.button(style=nc.ButtonStyle.blurple, label=button_one)
#@nc.ui.button(style=nc.ButtonStyle.blurple, label=button_one)
async def b_one(self, button: nc.ui.Button, inter: nc.Interaction):
inter.response.send_message("HI")```
He is not sending the button
well you're defining your b_one method then re-defining it inside your constructor method
Bro what app should I use
For what
smelling GPT
how do i fix then??
What do you have so far?
I need kick commands
We don't just write code for people for free. Do you have a specific question we could answer?
@bot.command() async def kick(ctx, member: discord.Member, *, reason=None): if ctx.author.guild_permissions.kick_members: await member.kick(reason=reason) await ctx.send(f'{member.mention} has been kicked.') else: await ctx.send('You do not have the required permissions to use this command.')
just adjust ur stuff
{ "choices": [ "Option1", "Option2", "Option3", "Option4", // Add more options as needed ] }
go acc to what ever u need @umbral bay
I think autocomplete is called whenever the user edits their input (which can be very often) so opening your file every time is less than ideal
might as well open once and cache the results
!d discord.Member.kick Check the docs on kicking members and try to build your own command around it. Remember that Discord already has this built-in so perhaps think about ways you can introduce new functionality into your command.
await kick(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Kicks this member. Equivalent to [`Guild.kick()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.kick).
@slate swan read after this message
I have linked a gist, follow that
oke
!d discord.app_commands.autocomplete There's an example implementation on the docs. Essentially you're just writing a function that returns a list of choices depending on the user's current input
@discord.app_commands.autocomplete(**parameters)```
Associates the given parameters with the given autocomplete callback.
Autocomplete is only supported on types that have [`str`](https://docs.python.org/3/library/stdtypes.html#str), [`int`](https://docs.python.org/3/library/functions.html#int), or [`float`](https://docs.python.org/3/library/functions.html#float) values.
[`Checks`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check) are supported, however they must be attached to the autocomplete callback in order to work. Checks attached to the command are ignored when invoking the autocomplete callback.
For more information, see the [`Command.autocomplete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command.autocomplete) documentation.
Warning
The choices returned from this coroutine are suggestions. The user may ignore them and input their own value...
My previous point simply was that you don't wanna be doing anything too heavy in your autocomplete callback, such as opening files or other blocking tasks, since it can potentially be called very often
How dare you being bigger spoonfeeder than me
lmao
@shrewd fjord still getting same error plz help
Can a Discord Bot display video in a VC?
no
Is there a way around this (not an exploit) but could I do it through an activity?
no
Ouch
Did you try it and see?
Try it out and let us know if there are any errors then
Make sure to include full traceback
You have a slash command decorator on an autocomplete function…
fruit isn’t defined as well
The first issue still persists
python bot.py
Traceback (most recent call last):
File "C:\Users\frrrrnamexdbot.py", line 3, in <module>
from discord_interactions import SlashCommand, SlashContext
ModuleNotFoundError: No module named 'discord_interactions'
bro holy shit iim not able to fix this shit im doing all stuff of fixing from 1hr help me plz 😭
It’s basic python
discord.py has built in slash command support
but why it is showing me same error when i run code
Well you’re not using discord.pys native slash command support
You’re using a 3rd party library
which one should i use for command??
nvm
Auto complete functions generally shoudnt have any decorators
Why is that? 
Probably should rephrase. They shouldn’t have decorators from the discord.py library
If you need your own custom decorators it’s fine
No
@slash.slash(
name="create-ticket-panel",
description="Create a ticket panel"
)
@commands.has_permissions(administrator=True)
async def create_ticket_panel(ctx: SlashContext):
# Implement logic to create a ticket panel
await ctx.send('Creating a ticket panel.')
im using this rn it stills show same error lmao
python bot.py
Traceback (most recent call last):
bot\bot.py", line 3, in <module>
from discord_slash import SlashCommand, SlashContext
ModuleNotFoundError: No module named 'discord_slash'
@final iron
nope
im getting the error in terminal prompt 😭
You shouldn't be surprised by the overwhelming number of outdated tutorials for Discord bot development in Python
oh yea i forgot about that
It's not slash.slash. You don't install discord_slash
then?
is it ext.commands.Bot??
It's under discord.app_commands and you should already have it if you installed discord.py version 2+
from discord import app_commands
Bots should have a tree attribute which you can use like @bot.tree.command() to create application commands
I think every bot has one initialized but I'm not sure
so should i use @bot.tree.command()???
import discord from discord.ext import commands from discord_slash import SlashCommand, SlashContext
i was using this first lmao
In any case, you also need to sync application commands with a guild or wait an hour for them to show up or update
Just remove the last line
oke
yh the commands r synced from start lol
For syncing
async def on_ready():
print(f'Logged in as {bot.user.name} ({bot.user.id})')
try:
synced = await bot.tree.sync()
print(f"Synced {synced} slash commands.")
except Exception as e:
print(e)```
`
Event when the bot is ready
@bot.event
async def on_ready():
try:
await bot.change_presence(activity=discord.Game("Made by melon"))
print(f'Logged in as {bot.user.name}')
except Exception as e:
print(f'Error in on_ready: {e}')`
ikr
Probably want the len() of that
slash = SlashCommand(bot, sync_commands=True) ^^^^^^^^^^^^ NameError: name 'SlashCommand' is not defined
wtf
holy i hate these errors lmao
Why do you even use that outdated stuff
how do i fix da shit?
Step 1: You don't use it as you don't need it
discord.py has built-in slash commands support
it will be probably something like this:
@bot.tree.command(name="createpanel", description="Create a ticket panel.")
async def createpanel(ctx: discord.Interaction):
#Implement logic to create a ticket panel
return await ctx.send('Creating a ticket panel')
No need to get some third party stuff
If you care about it, you should be creating the bot by passing the activity into the constructor in order to start the bot with an activity, instead of doing this in on_ready. Every other initialization should be done in bot.setup_hook
k
also that's not syncing anything
Why do you name the interaction object as ctx? Those are two different things
Only if you’re using the Bot extension
That's what it means to use a bot. Using a client as in from the client class does not provide this functionality
i did same stuff u told but
line 10, in <module>
slash = SlashCommand(bot, sync_commands=True)
^^^^^^^^^^^^
NameError: name 'SlashCommand' is not defined
lmao
You can still use Client to create slash commands
u need to take that line out and replace it with:
import discord
from discord import app_commands
Why are you using a 3rd party library. Discord.py has built in support
It is possible but I think the client classes provide zero command handling whatsoever
Nah
im using @bot.tree.command
also melon this code will not work since it does not have the code of creating the panel
Same as Bot, expect you have to initialise the tree yourself
Using Bot automatically does it
import discord
from discord.ext import commands
Then you don’t need a slash client or whatever
I guess so. The client classes do have interaction handling, right?
They do
add this too:
from discord import app_commands
yh
This won’t directly solve the issue
again dat fricking error
Here is a short example of how to use discord.py's slash commands as well as general information on them:
https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f
This currently covers free commands and groups at the Bot level, as well as within Cog classes.
It also includes information and gotchas relating to syncing and whatnot.
NOTE: This will be migrating to https://about.abstractumbra.dev/ as soon as I can be bothered to finish it.
My site for random things and stuff. Including a custom pip index and walkthroughs, both for discord.py!
wtf is going on
No shit
You’re using a 3rd party library
It doesnt exist in discord.py
It won't disappear unless you remove what makes it appear
melon send your code
what to do exactly xd
kk
@slate swan Read this
Remove line number eleven
i saw that but didnt understand any stuff lol
oke
Still won’t solve the problem
done
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
It's a step towards removing what needs to be removed
line 51, in <module> @bot.tree.command( ^^^^^^^^^^^^^^^^^ TypeError: CommandTree.command() got an unexpected keyword argument 'options'
😭
Read the guide. You’re trying to use things that don’t exist
Well yeah a lot of steps need to be done
This isn’t how coding works. You can’t just randomly add things and expect it to work. Read the guide
@slate swan change your bot's token now
what command should i use tho?? @bot.tree.command or what?
yes will do it rn
Read the guide
mhm
It literally explains everything
dats toolong wtf
It’s not
...
It’ll be way faster than completely restarting your code, and having somebody spoonfeed everything to you
this?
:(
Considering it doesn’t mention slash commands, no
where is guide then
sorry im too irritating xd
Above.
python bot.py
[2023-10-11 23:20:40] [INFO ] discord.client: logging in using static token
[2023-10-11 23:20:43] [INFO ] discord.gateway: Shard ID None has connected to Gateway (Session ID: e917732981d7690bdf7ea63a667650b9).
Logged in as BotX-acc-lister
holy
lol
What are you asking for specifically? How to create options?
What are the files? Python files?
What your code rn?
I have a dict with the select option as the key, and a function as the value
Well the function object
huh?

