#discord-bots
1 messages ยท Page 228 of 1
maybe
https://bitly.com/
U can choose the link, such as mine is bitly.com/mybotsname
Hi hope everyone is doing well im trying to create a welcome message whenever someone joins server, i know how to create this and i created it like i usually do ,
but whenever someone joins nothing happens at all
ofc i checked my intents but my intents were all enabled so im confused to as why the bot is not picking up whenever someone joins
ur intents is enabled, ok.
do u have ur intents set in ur main.py file too?
yes
this is my client initialisation code
url shorteners dont seem to work with these type of urls
noramlly this code works perfectly whenever i run with other bots
I guess I'll have to use the long url
depends on the library, in discord.py you'd use the tasks.loop(time=) argument
seems nextcord has it too, but assumes naive datetimes are in UTC
you can hyperlink a text
[here](your_link_goes_here)
so if you want to hyperlink https://youtube.com
nvm
haha
i never read that mb
its okay, thanks
What is problem with having https
Yes.. but that loop would restart if bot restarts, yes?
I want it to run exactly at 00:00 and 12:00
oh
thats the point of the time argument, it sleeps until said time is reached
im not sure on how to do that sorry
im not sure why the bot cant pickup joins
ooo O_O ok, bet, ill try that out, ty
no problem
seems to have been a discord limitation for a while
https://github.com/discord/discord-api-docs/discussions/3347#discussioncomment-952952
Whats the problem here
Can anyone help me with my issue
Explain
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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Your about me reminds me of michael jackson
And your every linked account have same name
thats what i thought, thanks
its in this message
here
Whats the terminal output
maan
nothing
Maybe share your whole command
don't change_presence on_ready
that is why i put print()
ive heard too many people tell em that lol
ok
lemme get that tag
Don't change_presence (or make API calls) in on_ready within your Bot or Client.
Discord has a high chance to completely disconnect you during the READY or GUILD_CREATE events (1006 close code) and there is nothing you can do to prevent it.
Instead set the activity and status kwargs in the constructor of these Classes.
bot = commands.Bot(command_prefix="!", activity=..., status=...)
As noted in the docs, on_ready is also triggered multiple times, not just once.
Basically: don't ๐ do ๐ shit ๐ in ๐ on_ready.

ok ill try changing tthat
Which client are you really using
Did you tried channel id
its not a problem with that
if you look i said at beginningprint("someone joined"
but nothing is printed meaning bot does not realise someone joined
Try putting commands.Client maybe just MAYBE it will help idk
Why did they make the event if they don't want anyone to use it
Im not much familier
I've always been wondering
should i use == or is on ChannelType?
you use it for like a print
@outer parcel show the whole code then it'd be clearer
but you'll see over a couple days that it's printed multiple times
calm
no....
!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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
pasted
Save it and send the link
No wonder
Oops, forgor to turn off reply
he forgor
if u say guild id
Why did you init a client instance twice
You're overriding the variable
both will work in this case as long as you're comparing the enum member itself, which is basically a necessity for a regular Enum subclass
where it does matter is if its a mixin for another class like IntEnum, and you're attempting to compare an instance of a different type ```py
class MyEnum(enum.IntEnum):
... FIRST = 1
...
MyEnum.FIRST is MyEnum.FIRST, MyEnum.FIRST == MyEnum.FIRST
(True, True)
MyEnum.FIRST is 1, MyEnum.FIRST == 1
(False, True)```
ty so much
i see
@app_commands.command(
name="test",
description="test")
async def test(self, interaction: discord.Interaction):
data = range(1, 20)
pagination_view = PaginationView()
pagination_view.data = data
await pagination_view.send(interaction) ```
```py
async def send(self, interaction: discord.Interaction):
self.message = await interaction.followup.send("test")
discord.app_commands.errors.CommandInvokeError: Command 'paginate' raised an exception: NotFound: 404 Not Found (error code: 10015): Unknown Webhook
have i made an error in the constructor of the send function?
does it not find the interaction?
you didn't defer it first
you have to defer it to send a follow up, or just use interaction.response.send_message
but then the send_message() doesnt return a message to edit it
use Interaction.original_response i think
If the interaction response was a newly created message (i.e. through InteractionResponse.send_message() or InteractionResponse.defer(), where thinking is True) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).
aright thank you very much
import os
import discord
import requests
import json
import random
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print('Logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!trivia'):
response = requests.get("https://opentdb.com/api.php?amount=1&type=multiple")
data = json.loads(response.text)
question = data['results'][0]['question']
answers = data['results'][0]['incorrect_answers'] + [data['results'][0]['correct_answer']]
random.shuffle(answers)
trivia_embed = discord.Embed(title="Trivia", description=question, color=discord.Color.blue())
trivia_embed.add_field(name="Options:", value="\n".join(answers), inline=False)
await message.channel.send(embed=trivia_embed)
for some reason its not responding without errors
Then what are the errors
there isn't any
You said there are 
you put not before it
Try putting on message intents both via gateway & the bot constructor
thank you
Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:
โข The message was sent by the client
โข The message was sent in direct messages
โข The message mentions the client
This applies to the following events...
import os
import discord
import requests
import json
import random
intents = discord.Intents.default()
intents.members = True
intents.nessages = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print('Logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!trivia'):
response = requests.get("https://opentdb.com/api.php?amount=1&type=multiple")
data = json.loads(response.text)
question = data['results'][0]['question']
answers = data['results'][0]['incorrect_answers'] + [data['results'][0]['correct_answer']]
random.shuffle(answers)
trivia_embed = discord.Embed(title="Trivia", description=question, color=discord.Color.blue())
trivia_embed.add_field(name="Options:", value="\n".join(answers), inline=False)
await message.channel.send(embed=trivia_embed)
so would this work?
yeah i tried but the edit and the send arent in the same fuctions
so i need to define in a way the message so i can edit it in another function
message_content not nessages
any1 has an idea?
import asyncio
import os
import discord
import requests
import json
import random
import traceback
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print('Logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
try:
if message.author == client.user:
return
if message.content.startswith('!trivia'):
response = requests.get("https://opentdb.com/api.php?amount=1&type=multiple")
data = json.loads(response.text)
question = data['results'][0]['question']
answers = data['results'][0]['incorrect_answers'] + [data['results'][0]['correct_answer']]
correct_answer = data['results'][0]['correct_answer']
random.shuffle(answers)
trivia_embed = discord.Embed(title="Trivia", description=question, color=discord.Color.blue())
trivia_embed.add_field(name="Options:", value="\n".join(answers), inline=False)
await message.channel.send(embed=trivia_embed)
except Exception as e:
traceback.print_exc()
def check_answer(m):
return m.author != message.author and m.content.lower() == correct_answer.lower()
try:
user_answer = await client.wait_for('message', check=check_answer, timeout=15.0)
except asyncio.TimeoutError:
await message.channel.send(f"Time's up! THe correct answer is {correct_answer}.")
else:
await message.channel.send(f"Correct! The answer is {correct_answer}.")
client.run('YOUR-TOKEN-HERE')
!d discord.Interaction.edit_original_response
await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
its not responding after the initial question
function argument?
i want to attribute to the file name the guild id where the command will be executed
Ok im creating a level up command and everything works only problem is
i searched up problem and i assumed i needed to do await client.process_commands()
but this did not work since process_command is not a thing anymore?
how would i do this now
it is, can you show your code
it's discord.ext.commands.Bot.process_commands
can someone tell me why my background task loop doesnt work? https://paste.pythondiscord.com/noqujojeca
it does not print anything after 5 for some reason```py
print("5")
channel=guild.get_thread(approved_papers_channel)
print("a")
no errors
hm ?
!dashm
When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.
Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.
Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.
Is there a specific function that waits for user to click the button before proceeding?
from a view? sure, use .stop() in the callback and .wait() to wait for the view to stop/timeout
which is the best sql database for a discord bot?
postgres or sqlite if your bot is small
it comes down to personal preference really @fading egret
alright, thank you
what are parameters
because it is asking me for them
i did this
actually client doesn't have commands unless you did client = commands.Bot() in the beginning of your code
i never
hence why i used commands.Bot
yeah use client instead of commands.Bot
you need an object to call process_commands on
for my code
show me the line with client =
so you defined client twice...
o
!e
variable = "Hello"
variable = "World!"
print(variable) ```
@cold sonnet :white_check_mark: Your 3.11 eval job has completed with return code 0.
World!
i see
how does it fix this thou
since client doesn't have commands
cuz it can't have commands
you don't need to process commands
again, await client.process_commands(message)
if you saw their code above you would see their client variable is commands.Bot
if you saw their code he redefined it
sure, that's not what they're intending to do
you're telling me he made a commands.Bot instance and proceeded to subclass discord.Client to use that subclass in the same code
I mean it's possible since run is a coroutine since 2.0
probably slow af
do you have commands in your bot
slash commands
These are all my code related to client
yes
prefix commands
message commands are the context menu commands you get when right-clicking a message
like with sir lancebot
o
thanks
i assume i do
but actually no command is appearing
since when can you make stuff like that
definitely not in your discord.Client subclass...
so how would i fix?
@outer parcel decide if you want prefix commands (e.g. !help) in your bot
no
remove process_commands and remove this part:
man put a yellow thumbsup so it's not just my black thumbsup reaction
show command
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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
paste the traceback too
thing is
i can run levle command once then if i try using it again it gives that error
ye so i found error
its only wrong with this level command because im using async with client.db.cursor() as cursor
I'd suggest closing that async with statement as soon as you don't use your database anymore
but I don't actually know why you get that error
how would i close
im not this acquainted with it
Hey, im trying to make modlogs & its giving me this error with webhooks.
Webhook views require an associated state with the webhook
i was testing to see if it would merge them lmao
are you trying to send buttons?
nope.
what's your code
im still having the problem :(
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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
this section causing problem
paste it please
async with aiohttp.ClientSession() as session:
webhook = Webhook.from_url('', session=session)
xx = await to_object(str(ce))
await webhook.send(**xx)```
the to_object is my embed parser to split things & make them an embed. currently the `ce` variable has {content: test}. this will send the message in a regular message. but it gives me that error
@smoky sinew
ye
what's to_object?
actually i went into the terminal
and saw again and it says error is here
cant send the full thing here. check your dms?
!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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
mudkip what is problem here
no
yes you are
you're creating an empty view and then passing it to be sent to the webhook
hm
webhooks cannot send views
because they have no way of receiving interactions from them
even URL buttons i'm pretty sure
hm. i see
im still having problem
if i run command it works
but if i run it again it does not
because it is repeating the command again for same image
what is the application/website that creates bots through Python?
i have noticed i can't link to an .ico files for the avatar_url in an embed, is there a way to get around that?
webhooks created by the bot actually can, its pretty dope
does anyone know a way i can get a list of commands, im using discord.py
in the code not discord
i found
bot.commands
!e print("test")
@latent sonnet :white_check_mark: Your 3.11 eval job has completed with return code 0.
test
does anyone know how i can organise commands into separate files like discord.js?
use cogs
It's called extension
i have cogs
ok
you should have multiple commands in one cog
im only starting discord.py
thank you mud kip
you shouldn't import cogs that's what extensions are for in the first place
sorry i just did discord.js before and i was wondering if it was posible
this channel is for asking some questions right
yes
so uh
your pfp is cute
i did a code thats like uh
if message.content.startswith('!hello'):
await message.channel.send('Hello!')
but the bot dont respond(its online)
Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:
โข The message was sent by the client
โข The message was sent in direct messages
โข The message mentions the client
This applies to the following events...
:O
good job
a
it means when its in 100 server it needs verify but not need when its not
thats what i thought
yeah and its not in 100+ right
ok
oh yeah
how
!d discord.Intents.message_content
Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:
โข The message was sent by the client
โข The message was sent in direct messages
โข The message mentions the client
This applies to the following events...
set this to True
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)```
still you're assuming that he's using default intents
yeah he might not be
@white peak wait arent you in my bots server?
oh yea im using default
it will work then
yeah
nice
Does anyone know discord.py well?
i found code on github who can try run it i need it for my business
ican pay
Does anyone have any good sources to look at for generating images within python? Iโm trying to create an image that represents location on a map, and I want to use co-ords or some such instead of 100 images and if/else statements etc. I want to be then be able to send said pic within a discord channel or dm
pillow? just make sure to run it in an executor
Iโve never used that before, any tips
And can u clarify what u mean by an executor
!d asyncio.loop.run_in_executor
awaitable loop.run_in_executor(executor, func, *args)```
Arrange for *func* to be called in the specified executor.
The *executor* argument should be an [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor "concurrent.futures.Executor") instance. The default executor is used if *executor* is `None`.
Example:
me neither honestly but i think it has good documentation https://pillow.readthedocs.io/en/stable/
you can just open a base image and overlay another image at whatever location you need
then save that to a temporary file and send it to discord
Why temporary file when random access memory exists?
i'm going to unrandom your memory
I see
So Iโm basically needing 2 images ?
Guess Iโll have to do some reading lol
sure that's one way you can do it
overlay one on top of the other
Is there a way for it to be a bit more flexible?
So I donโt need the second image
I guess it needs to know whatโs where โฆ
Anything is possible. All you need is objective requirements
Not everything is possible
yes dude
literally just do whatever you want
it was just a suggestion as to how you could do it
i don't even know what you're making
yeah ive been having a read
on the docs
im making a text adventure discord bot and i just wanted to be able to include a visual representation with a "You are here" arrow where the player is at the point in time
thats alg, thanks
you could do that with code but it would be easier to just get a png
and place it somewhere on the image and optionally rotate it
wdym?
w Pillow ?
yes
ah yeah
ive got pillow installed, gonna mess around w it and a test image, see how easy it is
How do you @ channels?
<@#1097084154400743465> is wrong apparently lol
nvm remove the @ ๐
keep in mind that TextChannel.mention exists if you're using Discord.py
oh
psh dont need
channel = await createcategory.create_text_channel(f"Clan Create #{len(createcategory.channels)}", overwrites=overwrites)
await interaction.response.send_message(f"{interaction.user.mention} - Please visit <#{channel.id}> to start and complete the clan create process.")
๐
channel.metion
but if you are wondering here are all formats
Ty ty appreciate it.
I don't see the issue with f"{interaction.user.mention} - Please visit {channel.mention} to start and complete the clan create process."
And I don't see an issue with await interaction.response.send_message(f"{interaction.user.mention} - Please visit <#{channel.id}> to start and complete the clan create process.")
It is computationally slightly slower, that is an issue, for me
How much slower?
if there is a built-in method that does it why implement it yourself again
Im not recreating it lol there's just 2 ways to get to the same destination
if you are geting the same result it is recreating
very little for a human, but still a lot for the computer when you have as little as 1000 users using it simultaneously
y u cross out
thinking about it now, I was wrong. However, Python is all about readability, and a word is more readable in this context than the raw syntax.
!e import this
@sullen shoal :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | The Zen of Python, by Tim Peters
002 |
003 | Beautiful is better than ugly.
004 | Explicit is better than implicit.
005 | Simple is better than complex.
006 | Complex is better than complicated.
007 | Flat is better than nested.
008 | Sparse is better than dense.
009 | Readability counts.
010 | Special cases aren't special enough to break the rules.
011 | Although practicality beats purity.
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/mawelorina.txt?noredirect
Neato
someone knows what does it mean? this problem in db or in code (yesterday it was working)
Do I need just wait or I need fix something?
I know bruh, but donโt have rn my main pc
I have no idea about that maybe ask in #databases
Iโve did it already ..
Try changing the db and running it and see if u get the same error
whats the method to get the bots username in app_commands ?
im tryiny to make an edit message check
It works but if i edit a previous message that was sent before the bot was turned on the bot just wont pick it up why is this?
Hi everyone, I got these problems with this code (its a discord bot) n idk why, I tried everything, can someone help me :/
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
how
indent them
just like this
like this
yes
@slate swan, @slate swan, look: https://replit.com/
I can't I don't have a replit account
discord.Interaction has a .client attribute which is your bot, you can use .user attribute to get the user, and .name for the name of it
u dont have to make a run_bot funktion u can just have client.run(TOKEN) at the end and the rest like this
ah, alright, thank you
@uneven swan look into the chat on replit
i did it a lot of times but
so u want the command to be /say {text} and then the text should be sent? or wdym?
you are using python 3.4 or older, and you need higher to use discord.py
upgrade to 3.7 or something imo
you mean you don't want the :
@slate swan used /say part ?
you should use interaction.channel.send
but note this
yh
not answering an interaction (like you are doing now with response.send_message) will make the command say this interaction didn't respond
await interaction.channel.send(...) # for users
await interaction.response.send_message("successfully sent text", ephemeral=True) # message only the user who used the command will see, used to remove the this interaction did not respond part
no not replace
here ephemeral=True will make the message only visable to you
your welcome
alright
thanks
is there a way to group slash commands?
You mean create sub commands?
yes
https://discordpy.readthedocs.io/en/stable/faq.html#how-do-i-make-a-subcommand
this is an example for prefixed commands but its almost the same for slash commands
i have this problem
what's the problem
idk
you can always hover over it and see
or just run your code
in any case, it's because you're using await outside an async function
which is not allowed
the bot is online but, it doesn't show any rich presence
this the code ```activity = Activity(
name="Test",
type=ActivityType.playing,
state="Test",
details="Test",
emoji={"name": "๐ฉ"}
)
await client.change_presence(activity=activity, status="online")```
you can't await outside async functions
and you can't change presence before the bot has logged in
use the activity kwarg in the constructer
i'm getting so lost rn, apparently can't I use .ico files as the url for avatar_url in an embed, is there's any way to get around this? the url is "https://raw.githubusercontent.com/r-ex/LegionPlus/main/Resources/LegionIcon.ico"
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
!d discord.ext.commands.Bot.activity
property activity```
The activity being used upon logging in.
i know
yo how
what
i found this on the internet, i dont even know how it works man
anyone got an idea how to get around this?
some knows this mistake with db and how to solve this ??
you mean sth like ```py
@app_commands.group()
async def item(self, interaction: discord.Interaction):
return await interaction.response.send_message("test 1")
@item.command()
async def sad(self, interaction: discord.Interaction):
return await interaction.response.send_message("test 2")
that won't work
slash group parents can't be invoked themselves
for example
if you have :
/parent and /parent child
then /parent won't be a valid command
!d discord.app_commands.Group
class discord.app_commands.Group(*, name=..., description=..., parent=None, guild_ids=None, guild_only=..., nsfw=..., auto_locale_strings=True, default_permissions=..., extras=...)```
A class that implements an application command group.
These are usually inherited rather than created manually.
Decorators such as [`guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only "discord.app_commands.guild_only"), [`guilds()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guilds "discord.app_commands.guilds"), and [`default_permissions()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.default_permissions "discord.app_commands.default_permissions") will apply to the group if used on top of a subclass. For example:
```py
from discord import app_commands
@app_commands.guild_only()
class MyGroup(app_commands.Group):
pass
```...
use this
aright, thank you
#m is a message object
regexp = re.compile(r' ')
match = re.split(regexp, m.content, maxsplit=2, flags=0)
await bot.get_channel(int(match[0])).send(match[1])
if match[1] is a hyperlink, it's an empty string and won't send
I suspect this is because of embeds, but if match[1] is text and a hyperlink it works fine
even trying to escape the link with <> around it behaves similarly
what obvious thing am I missing here
eh, nevermind
just made it check if the message has embeds and send it with or without embeds as necessary
how would i add options into my slash command
you say that the choices will be strings but the values are booleans instead
change it to app_commands.Choice[bool]
@commands.has_permissions(manage_roles=True)
async def create(self, ctx, user: discord.Member, *, role: discord.Role):```
im working on my role create command and idk how to finish it
somebody knows how to fix this
@app_commands.checks.has_role(1017279032171188265)
how to make it work for 2 role ids (no need to have them both so u can use it but u need atleast one of them to use the commands)
alright
im trying to keep my bot always online but i dont know how, replit is a solution rn
You might wanna take a look at #965291480992321536
has_any_role instead of has_role
i dont want any role to use it
i only want 2 roles to use it
Well then try adding an if statement to check if the person has both the roles
i dont need him to have both roles i need him to have one atleast of them
...
Bruh, you have has_any_role for that, if u want the command to work only for people which have at least 1 of the 2 roles
Hi Dani
Long time
can example of the has_any_role?
Hi Hunter yes
@app_commands.checks.has_any_role(id1, id2)
How u doing
discord.py keeps getting more complicated yet the issues here keep getting numb
Lmao
I mean not just telling people to learn the basics is a good thing but if people won't bother to learn python then this channel's gonna be flooded by dumb issues which aren't even related to the channel
most of the regulars are gone
True
I don't see any familiar faces here anymore, except sarth and Asher, that too once in a blue moon
He changed his name
he
mhm
Yea.... Long story
@shrewd apex would know
@commands.has_permissions(manage_roles=True)
async def role(self, ctx, user: discord.Member, *, role: discord.Role):
if role in user.roles:
await user.remove_roles(role)
else:
await user.add_roles(role)
@role.group()
@commands.has_permissions(manage_roles=True)
async def add(self, ctx, user: discord.Member, *, role: discord.Role):
embed=discord.Embed(description=f" **{role} was added to {user}**")
await user.add_roles(role,embed)
@role.group()
@commands.has_permissions(manage_roles=True)
async def remove(self, ctx, user: discord.Member, *, role: discord.Role):
embed=discord.Embed(description=f' **{role} was removed from {user}**')
await user.remove_roles(role, embed)``` im trying to run these commands but idk what to use? like ,roleadd??
no like ,role @summer canyon @role....
ok
oops wrong ping
damn it
but the role command is basically the same as the other two
you can use just
,add @gilded oxide role
or
,remove @gilded oxide role
@commands.has_permissions(manage_roles=True)
async def add(self, ctx, user: discord.Member, *, role: discord.Role):
embed=discord.Embed(description=f":add: **{role} was added to {user}**")
await ctx.send (embed=embed)
await user.add_roles(role)
@role.group()
@commands.has_permissions(manage_roles=True)
async def remove(self, ctx, user: discord.Member, *, role: discord.Role):
embed=discord.Embed(description=f':remove: **{role} was removed from {user}**')
await ctx.send(embed=embed)
await user.remove_roles(role)``` I want the embed to send but it wont
well it should
the role command doesn't have this embed part
@commands.has_permissions(manage_roles=True)
async def role(self, ctx, user: discord.Member, *, role: discord.Role):
if role in user.roles:
await user.remove_roles(role)
else:
await user.add_roles(role)
@role.group()
@commands.has_permissions(manage_roles=True)
async def add(self, ctx, user: discord.Member, *, role: discord.Role):
embed=discord.Embed(description=f" **{role} was added to {user}**")
await ctx.send (embed=embed)
await user.add_roles(role)
@role.group()
@commands.has_permissions(manage_roles=True)
async def remove(self, ctx, user: discord.Member, *, role: discord.Role):
embed=discord.Embed(description=f' **{role} was removed from {user}**')
await ctx.send(embed=embed)
await user.remove_roles(role)```
did you use the role command or one of the other ones
yea the role doesn't get removed
- see if you get an error
- if yes, send the error
if no, see if you have an error handler
this is a protocol I wanted to write while I was often here
- see if you get an error
- send the error if there is one,
else check for an on_command_error or an on_error event which doesn't have anelse: raise error - end the event with
else: raise error - run the code again and send the error
there was definitely more to that
Zeffo you have any guide on seting up logging in a discord bot? Or example
import logging
logging.basicConfig(level=logging.INFO)
something like this should be good
Never seen this thanks
i had the /test command i my bot earlyer
now i removed it from my code but its still showing up...
any1 knows how to remove it?
sync
sync your commands
no one got an idea about this?
can somone help me on discord embeed
probably, but people are very unlikely to say yes unless they know what specifically you need help with
It's the difference between "Can someone help me with a website" going between "Oh it just has to have my picture on it" and "the next facebook, you can do it for free right?"
Convert to png and put as file ig
Pillow can probably do that
This website help ig
ty
the thing is i want to use that image url because it's being changed as the tool is being updated, and i don't wanna do it manually every time
why the hell this error is happening?
it's the first time it happens to me:
import bot_token
import discord
from discord.ext import commands
import os
import asyncio
client = commands.Bot(command_prefix='rpu->', intents=discord.Intents.all())
@client.event
async def on_ready():
print("Sucess: Bot is connected to discord!")
async def load():
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
await client.load_extension(f"cogs.{filename[:-3]}")
async def main():
async with client:
await load()
await client.start(bot_token.return_token())
asyncio.run(main(), debug=False)
that's not a problem with your code
you're trying to run your code in the python REPL
exit the python REPL using quit() before running your code
also you should use setup_hook to load your extensions
yeah its kind of weird that the python plugin doesnt bother to check if it looks like a repl before attempting to run the file
well, i just closed the terminal and now it's back working
How can i host my discord bot 24/7
Hi guys, i have a code that get some options from a yml file and creates an option for a dropdown menu with them it works fine but i dont know how to make a callback for every option. The callback should change the channel name and it is also specified in the configuration file.
This is my yaml file
dropdown:
#You can create as many options as you want, Max is 25 (Discord Limitation)
option1:
name: "Account"
description: "For issues regarding your in-game account."
emoji: ":bust_in_silhouette:"
ticket_name: ":bust_in_silhouette:โaccount-{interaction.user.name}"
option2:
name: "Store Support"
description: "For issues regarding the store and payments."
emoji: ":money_with_wings:"
ticket_name: ":money_with_wings:โstore-{interaction.user.name}"
This is how i get the values:
menu_options = [
discord.SelectOption(label=dropdown[option_key]['name'], description=dropdown[option_key]['description'],
emoji=dropdown[option_key]['emoji'])
for option_key in dropdown
]
And this is my dropdown:
@discord.ui.select(placeholder=ticketchannel['dropdown_placeholder'], min_values=1, max_values=1, options=menu_options,
custom_id=f"menu")
if each option has the same structure you'd likely be fine writing a single callback for your select menu, but otherwise you can abstract each option into a separate set of classes
There isn't a way to check if the selected values is equal to the first label name, if not it checks if it is equal to the second and so on.
how do i add a discord bot token in pycharm?
sure there is, it can very literally be written as you described py @discord.ui.select(...) async def my_select(self, interaction, select): for option in select.options: if select.values[0] == option.label: break though practically you might prefer discord.utils.get() instead: py option = discord.utils.get(select.options, label=select.values[0]) or even better, a dictionary mapping your option values to the corresponding entry in your config
you... type it? or store it in a file and retrieve it (python-dotenv is a common package for this)
Got it to work like that, thanks
for option_key in dropdown:
if select.values[0] == dropdown[option_key]['name']:
await interaction.channel.edit(name=f"{dropdown[option_key]['ticket_name']}".format(USERNAME=interaction.user.name))
await interaction.response.edit_message(view=CloseButton())
in your case i would prefer to set the option value to the corresponding yaml key and then use that for the lookup, its a bit nicer to write ```py
menu_options = [discord.SelectOption(label=option["name"], value=name) for name, option in dropdown.items()]
option = dropdown[select.values[0]]
await interaction.channel.edit(name=option["ticket_name"])``` editing channels also has a heavy ratelimit iirc so you might want to defer() beforehand
How can I apply ratelimit for multiple functions?
huh ?
im very confused can someone explain what is happening
i copied this code from google i just wanna test discord bots first
** i think** you have to install discord module
CTRL + R --> cmd --> pip install discord
anyone knows how i can sync the tree commands to everyserver the Bot is on?
you'll probably need to write a custom check for that involving app_commands.Cooldown or commands.CooldownMapping
bot.slash_command() only exists in certain libraries and certain versions, e.g. pycord and nextcord
oh i have to install pycord ?
if you're using dpy 2.0 there's a different syntax for slash commands
oops wrong reply

domi you can iterate through client.guilds during that on_ready event and sync each one
yup, though i would prefer to sync from a prefix command since on_ready can fire multiple times (depending on how frequently you restart your bot and connection stability), and syncing has a daily ratelimit
Pretty sure if you leave out the guild argument tree.sync() syncs to all your guilds by default
Why bot.close() gives me this error? It works but throws this in console
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000002860AE0C9D0>
Traceback (most recent call last):
File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 746, in call_soon
self._check_closed()
File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000002860AE0C9D0>
Traceback (most recent call last):
File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 108, in close
File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 746, in call_soon
File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 510, in _check_closed
RuntimeError: Event loop is closed
Can you use while True and try in the same code as this?
while True:
try:```
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.
Looks like google has a lot of results
Iโve been using replit but itโs quite unreliable
but the big ones are AWS, Azure, or Google Cloud
Do you use any ? That are trusted
The three I mentioned are the most trusted
Any tutorial on how to use them
There are plenty on youtube
Ty
The ratelimit is for the API calls and not the command itself
Which api calls.
how would I make these events for my antinuke
on member ban
on member remove
on guild update
on guild channel create
on role create
on role permission added
What do you mean
make these events for my antinuke
like I know how to start them off but how do I give it attributes for example on member ban their perms need stripped
like if you detect nukage remove the persons perms?
not sure what you mean by giving it attributes
I am having trouble understanding what you are trying to say.
just make them
if you want a good way of making an anti-nuke, create a base Check class
and each Check can have its own events
wtf is that.
and then once a user failed too many checks ban them
yes
thats a good idea but idk how when u say base check class?
like make a class of checks?
question. so when you're using super.__init__ in a view. if you have a function in the main class, do you need to set it as a parameter to run it in the view?
like for a randomizer. to repeat the function. would you want to use the randomizer in the __init__ or in the super.__init__for the view?
can u explain in my forum #1097314872120840223
Why make a base check class 
it would be more of an abc really
Idk why u would need an asbtract base class for a check...
Unless ur gonna have a check class per event, which is a bit inefficient.
it's mostly one check per multiple events
this way you can set severity too
e.g. banning members is worth 3 points, adding a webhook is worth 1
10 points within 5 minutes = ban or something similar
Riot API
thats more of a #software-architecture question then
essentially making an api wrapper like dpy, though it probably wont have to be anywhere as complex
nvm, answered my last question. also, bump
if only the subclass of View uses it, pass it to the subclass
e.g. ```py
class MyView(discord.ui.View):
def init(self, *, special_argument):
super().init()
self.variable = special_argument
so it would go in the base initializer and not the super? def __init__(self, *, special_argument) not the super().__init__(special_argument)?
You pass the arguments of the class you're inheriting in the super().__init__()
!e
class Base:
def __init__(self, a):
print(a)
class Sub(Base):
def __init__(self, a, b):
super().__init__(a)
self.b = b
Base("uwu")
Sub("owo", "meow")
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | uwu
002 | owo
o.o that makes so much sense. ty
does someone know how to do data bases?
i do
dms
uh ok

The Bases of Data
can anybody tell me the meaning of os.system('cls')
You can simply โclsโ to clear the screen in windows.
Is there a documentation for the os module ?
!d os
Source code: Lib/os.py
This module provides a portable way of using operating system dependent functionality. If you just want to read or write a file see open(), if you want to manipulate paths, see the os.path module, and if you want to read all the lines in all the files on the command line see the fileinput module. For creating temporary files and directories see the tempfile module, and for high-level file and directory handling see the shutil module.
Notes on the availability of these functions:
Thanks
@commands.group(name="configure", invoke_without_command=True)
@commands.has_permissions(administrator=True)
async def configure(self, ctx, key:str, value:str):
config_item = getattr(self.bot.config, key, default=None)
value = value.strip()
if not config_item or not value:
await ctx.send("Config item or value not found")
return
item_type = type(config_item)
if item_type == bool:
if value.lower() == "true":
setattr(self.bot.config, key, True)
await ctx.send(f"{key} set to True")
elif value.lower() == "false":
setattr(self.bot.config, key, False)
await ctx.send(f"{key} set to False")
else:
await ctx.send("Invalid entry ( True | False only)")
elif item_type == int:
if value.isdigit():
setattr(self.bot.config, key, int(value))
await ctx.send(f"{key} set to {value}")
else:
await ctx.send("Invalid entry ( Integer only )")
elif item_type == str:
setattr(self.bot.config, key, value)
await ctx.send(f"{key} set to {value}")
elif item_type == list:
split = value.split(",")
for i, val in enumerate(split):
split[i] = val.strip()
# If list provided
if len(split) > 1:
setattr(self.bot.config, key, split)
await ctx.send(f'{key} set to {split.join(", ")}')
else:
if value in config_item:
config_item.remove(value)
await ctx.send(f'Removed {value} from {key}')
else:
config_item.append(value)
await ctx.send(f'Added {value} set to {key}')
else:
await ctx.send("Unsupported config item type")
How bad of an idea is this
It's specifically for my server
I was too lazy to write commands for each config item so I instead write this which probably took about the same amount of time
But I mean... now any value can be set as I add it to the config without me having to add a "setter"
A new Chapter! Happy spring everyone !!
ะบะฐะบ ััะธัั python, ะณะพัะฟะพะดะฐ?
ะะพ ะฒะพะทะผะพะถะฝะพััะธ ัะตะบะพะผะตะฝะดัะตััั ะธัะฟะพะปัะทะพะฒะฐัั ะฐะฝะณะปะธะนัะบะธะน, ัะฐะบ ะฑะพะปััะต ะปัะดะตะน ัะผะพะณัั ะฟะพะฝััั ะธ ะฟะพะผะพัั
What is self.bot.config
So what is the best framework that is feature rich and mostly future proof.
Also is discord.py dead?
no discord.py is in active developlment
and I myself use discord.py and suggest it but it doesn't support some stuff such as voice recieve
What would you use received voice for anyway
its useful in special cases but yeah not needed for most people
I think it's discord bot related. I just want to limit the aiohttp requests per minute.
So it won't reach the ratelimit
hi i have made a bot how would i give it multiple prefixes and how would i make a command with different names
same function different names
like status and stats for 1 command i dont wanna copy paste i feel like there could be a better way
ratelimiting is a pretty common task that isnt related to discord development, there's even libraries out there dedicated to it https://pypi.org/project/limiter/
though i guess in the context of aiohttp #async-and-concurrency would be a more relevant place
depends on the library you're using, if its discord.py the commands.Bot(command_prefix=) parameter can take a list of prefixes instead of one, and the @command() decorator has an aliases= parameter for providing alternative names
ty found it
And what is https://pypi.org/project/ratelimit/ for?
What is the difference?
just based on their pip descriptions, ratelimit doesnt appear to support async/await
So is this how you would use it?
from limiter import AsyncLimiter
limiter = AsyncLimiter(max_calls=200, period=60) # limit to 200 requests per 60 seconds
async def get_summoner_name(summoner_id, RIOT_API_KEY):
url = f"https://euw1.api.riotgames.com/lol/summoner/v4/summoners/{summoner_id}"
headers = {'X-Riot-Token': RIOT_API_KEY}
async with limiter: # acquire lock
async with aiohttp.ClientSession(headers=headers) as session:
async with session.get(url) as response:
if response.status == 200:
json_data = await response.json()
return json_data["name"]
else:
await asyncio.sleep(10)
continue
limiter.release() # release lock```
Why are you calling .release()
They should be releasing it automatically after the async with block ends
Oh I see thanks. So the rest is fine?
Probably
ah aiolimiter was what i was initially looking for but forgot the name of
how do i make a command wich deletes the trigger( for example i use ?help and then the bot deletes it)
So currently if I want a new "Model" (The pop up input field)
I have to do this:
class ClanNameForm(discord.ui.Modal, title="Clan Name"):
def __init__(self):
super().__init__()
ClanName = discord.ui.TextInput(
label="Clan Name",
placeholder=f"Your clan name here.",
required=f"True",
)
async def on_submit(self, interaction: discord.Interaction):
check_if_exists = await db.get_clan_by_name(clanname=self.ClanName.value)
if check_if_exists:
await interaction.response.send_message(f"The clan name: `{self.ClanName.value}` is already reserved or registered. Please submit a new one.", ephemeral=True)
return
await interaction.response.send_message(f"{self.ClanName.value} has been registered.", ephemeral=True)
Is it possible to do something similar to embeds? where it's like:
embed = discord.Embed()
embed.add_field()
Or would I need a new class for each form/modal?
ctx.message refers to the message that triggered the command, so you'd call .delete() on that to delete it
ty
So this would do it?
from aiolimiter import AsyncLimiter
rate_limit = AsyncLimiter(200, 60) # Limit to 200 requests per 60 seconds
async def get_summoner_name(summoner_id, RIOT_API_KEY):
url = f"https://euw1.api.riotgames.com/lol/summoner/v4/summoners/{summoner_id}"
headers = {'X-Riot-Token': RIOT_API_KEY}
async with rate_limit: # use AsyncLimiter
while True:
async with aiohttp.ClientSession(headers=headers) as session:
async with session.get(url) as response:
if response.status == 200:
json_data = await response.json()
return json_data["name"]
else:
await asyncio.sleep(10)
continue
@bot.command(aliases= ["Help"])
async def help(ctx,):
embed = discord.Embed(title="Need help for commands?", description= "List of all the commands:", color=discord.Color.blue())
embed.add_field(name= "Beta/beta", value="By using this command you will be putted in a review list to be part of the beta tester team.")
embed.add_field(name="Report/report", value= "This command is used for reports, Command structure= ?Report @user reason ")
await ctx.send(embed=embed, delete_after=30)
await ctx.message.delete()
Will this work?
dynamic textinputs is possible through .add_item() iirc, if you think its worth re-using the same on_submit for multiple text inputs
assuming your bot always has the manage messages perm sure
Well I can just return the value right?
and how do i mention the user who used the command?
ctx.author.mention?
ok
i imagine you could create a modal instance, add text inputs to it, and then wait() for those inputs to be filled out, but ive never actually tried that before
so how do i add it
@bot.command(aliases= ["Help"])
async def help(ctx,):
embed = discord.Embed(title="Need help for commands?", description= "List of all the commands:", color=discord.Color.blue())
embed.add_field(name= "Beta/beta", value="By using this command you will be putted in a review list to be part of the beta tester team.")
embed.add_field(name="Report/report", value= "This command is used for reports, Command structure= ?Report @user reason ")
await ctx.message.delete()
await ctx.send(embed=embed, delete_after=30,)
Should I add a small delay after each successful request?
it would help your ram
So this is my final code for it:
from aiolimiter import AsyncLimiter
rate_limit = AsyncLimiter(200, 60) # Limit to 200 requests per 60 seconds
async def get_summoner_name(summoner_id, RIOT_API_KEY):
url = f"https://euw1.api.riotgames.com/lol/summoner/v4/summoners/{summoner_id}"
headers = {'X-Riot-Token': RIOT_API_KEY}
async with rate_limit: # use AsyncLimiter
while True:
async with aiohttp.ClientSession(headers=headers) as session:
async with session.get(url) as response:
if response.status == 200:
json_data = await response.json()
await asyncio.sleep(0.3) # add 0.3 second delay
return json_data["name"]
else:
await asyncio.sleep(10)
continue```
should work
however only a way to know
I mean, if you guys know of any better way to do this, I'm open to hearing your proposition
default_color = configData["DEFAULT_COLOR"]
TypeError: Expected discord.Colour, int, or None but received str instead.
is it possible to store the 0x56e2f5 inside the json otherwise?
or just convert it in the call, but in which type?
discord.Colour, int, or None
Straight forward, isn't it
store it as int
it actually is int
!e print(type(0xffffff), 0xffffff)
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
<class 'int'> 16777215
but how do i store 0x56e2f5 as an int if it has characters?
how did you get the int code?
Just cast it to int
It's a hexadecimal representation
!e ```py
print(int("0xffffff", 16))
What the
dont forget the second argument
Oh yes
@vocal snow :white_check_mark: Your 3.11 eval job has completed with return code 0.
16777215
Ty
(even better would be using a file format that supports hex like toml/yaml)
aright thanks
!d discord.Colour.from_str *
classmethod from_str(value)```
Constructs a [`Colour`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Colour "discord.Colour") from a string.
The following formats are accepted...
this color preview thing is kinda nice ๐ค
.color hex c0ffee
the script cannot find the module import yaml...
did the pip installed it in the wrong place?
red is not valid hex value !
do you get an ImportError?
.color hex c0ffee
reee
the install package button there should work
and you're right, pip installed it in the wrong place because pycharm creates a venv for each project
admin privileges :{
Thus the reee
yeah worked, thank you
I did give the channel though
yes yes
is there a way to get the bots avatar url in a slash command?
something like interaction.client.user.avatar_url ?
.avatar.url
thanks
Also this will error if it has a default avatar
So just to confirm "async with rate_limit:" will make the function sleep until the limit is over, and try again?
auto generated by docs?
hi, how to code a percentage of chance?
exemple: "a" and "b"
if a=56%:
send message
please help me
ask in #1035199133436354600 / #โ๏ฝhow-to-get-help for basic python questions
I am new to programming, please explain to me the solution
show what you put as token when starting the bot
what is the point of puting the token to .env when you put it to getenv
!dotenv
.env (dotenv) files are a type of file commonly used for storing application secrets and variables, for example API tokens and URLs, although they may also be used for storing other configurable values. While they are commonly used for storing secrets, at a high level their purpose is to load environment variables into a program.
Dotenv files are especially suited for storing secrets as they are a key-value store in a file, which can be easily loaded in most programming languages and ignored by version control systems like Git with a single entry in a .gitignore file.
In python you can use dotenv files with the python-dotenv module from PyPI, which can be installed with pip install python-dotenv. To use dotenv files you'll first need a file called .env, with content such as the following:
TOKEN=a00418c85bff087b49f23923efe40aa5
Next, in your main Python file, you need to load the environment variables from the dotenv file you just created:
from dotenv import load_dotenv()
load_dotenv(".env")
The variables from the file have now been loaded into your programs environment, and you can access them using os.getenv() anywhere in your program, like this:
from os import getenv
my_token = getenv("TOKEN")
For further reading about tokens and secrets, please read this explanation.
Also, don't leak your bot token. Please reset it
thank
why not ๐
Because people can get full access to your bot and do anything with it
i was sarcastic
I make exactly that face when being sarcastic
you're my second account

cool
Nice
epic
awesome
unbeliavable
sheesh
Anyone has a idea what kind of bot i could make?
You can make anything, really
The possibilities are endless :3
ik but i dont know what i should do tbh
!projects has a list of ideas
The Kindling projects page on Ned Batchelder's website contains a list of projects and ideas programmers can tackle to build their skills and knowledge.
You could incorporate any of those into a discord bot without too much effort
Thanks!
What is the most efficient way to run tasks every third day?
hours=24*3
I have a feeling that "@tasks.loop(hours=72) " is giving me "Can't keep up, shard ID None websocket is 37.4s behind."
I don't know what else it could be
Common symptom of blocking functions
So @tasks.loop is a blocking function?
No
The blocking function could be anywhere in your code
Not strictly restricted to the task itself
Would you review my code and help me out? Because I cannot find it ๐ฆ
are you using requests?
iirc there were some asyncio things that you could setup to debug your code
Do you have a git repo or something I can take a look at?
I can upload it on https://paste.pythondiscord.com/ and DM you the link
I prefer if it was kept here if possible
I don't feel like sharing my entire bot to the public
It's just for the link, we can keep the conversation here
Alright, that's fine
@young dagger looks fine for the most part - might be the usage of Pymongo?
It's also wholly possible either your host machines network fell behind or Discord fell behind or anything in between so it may not even be with your code
anyone know how to fix this
I'm using motor no?
Sorry but can you show me the part were I'm using pymongo?
show the full error first
dont name your file discord.py as its the module name
same problem occured
how can i know if user have boosted the server one time only or multiple times
I think that is just for the "ReturnDocument.AFTER" since motor doesn't have that.
counter_doc = await counter_collection.find_one_and_update({"_id": "case_counter"}, {"$inc": {"count": 1}},
return_document=ReturnDocument.AFTER)```
i fixed it ty
how do i make the bot active btw
๐ญ sorry im kinda new to this
sorry i dont get you
i legit started yestarday and thought i would try testing with bots im rusing things huh ๐ญ
Add client/bot.run('token') at the end of code
Where token= bot token u get it from dev portal
everyone
okk ty
But that's the simplest way i know of explaining after u already told them about run function
something like this, py ctx.server.id = ctx.server.id with open(f'users_data\{ctx.server.id}.json', "w") as users_data : json.dump(test, users_data)
i want to attribute to the file name the guild id where the command will be executed
discord module you mean
?
oh ok
๐น yeah i'm using it
Yeah discord uses guild to describe server

๐น
but i want to arribute to my file name a value that i don't know :/
idk how to process
I guess so
No, using x will raise an error if the file already exists
Maybe they want to replace it if it already exists ?
?????
anyone have a sample code for discord.ui.Button use?
Using https://motor.readthedocs.io/en/stable/api-asyncio/asyncio_motor_collection.html#motor.motor_asyncio.AsyncIOMotorCollection.find_one_and_update from pymongo import ReturnDocument
So I'm only using it for ReturnDocument.AFTER
passe dm, jsuis plus ร l'aise en francais pour t'expliquer mon soucis :D
any ideas on hwo could I host my bot and the bot's website at the same time?
I was thinking of having 2 python instances but idk if that's ok
Yeah you shouldn't run them in one terminal
Use one for bot and another for site
They can communicate with ipc
ipc?
hello
@code_bot.tree.command()
async def test(interaction: discord.Interaction):
await interaction.response.send_message("Hello")
await interaction.response.edit_message(content="Hello edited")
i am trying to edit the message i send as response to user but it is giving me error
can someone tell me what i am doing wrong?
!d discord
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
which error?
InteractionResponded: This interaction has already been responded to before
this one. i have been trying to solve it but couldn't solve it
discord.Interaction.followup
discord.Interaction.followup returns a webhook
which you can edit via
id recommend edit_original_response instead, but i wonder if that method actually works with an interaction webhook
hmmm
!d discord.Interaction.edit_original_response
await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
that one doesn't work
how so
!d discord.Interaction.message
The message that sent this interaction.
This is only available for InteractionType.component interactions.
it says webhook object is not callable
send error and code
interaction.message would be using the regular discord API rather than what's provided by the interaction
hmm
why not use that?
Command 'test' raised an exception: TypeError: 'Webhook' object is not callable
i think it only works if you have a bot account in the server and read/send perms in that channel
I mean
this is replying to the message
isn't the response a message?
not editing it
or it doesn't count as one because it is an app command
await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
its not the same kind of message, dpy makes it look like a message but there are different endpoints for modifying that message
makes sense then
has it changed?
what do i do now?
how does it not work? this is the standard way of editing a response after its been sent
it says interaction doesn't have that attribute
what library are you using?
and version?
latest
which one is latest now im wondering
what does latest mean, like the last time you used pip install git+https://github.com/Rapptz/discord.py?
!d discord
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
do pip show discord.py
today
2.2.2
btw showing a full traceback is more helpful, use https://paste.pythondiscord.com/ if you think its too long

