#discord-bots
1 messages ยท Page 107 of 1
have you saved the file?
and show your code pls
commands can have parameters, i suggest to read the explanation in this page https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#parameters
noted 
this should work, are you using a venv?
btw don't make Api calls on on_ready event, don't load extension inside it too, on_ready is an event that could be dispatched multiple times so you'll probably get an error while loading the extensions (like extension already loaded)
idk am new so
its says env
so idk
where it says env
oh dotebv
Don't change presence in on_ready. Use the activity kwarg in your bot constructor instead
dotenv*
dotenv is another thing
o.o what?
Read the second part here
i have but all works but its the terminal stuff i need help with tho
You're changing your bot's presence whenever on_ready is dispatched, don't do that
so am going to change that to?
You should be able to instantiate the bot with a presence
commands.Bot has an activity kwarg where you can pass in whatever activity you want instead of using on_ready
ok i have used the same code in an other bot and that worked but the terminal is not working tho
what am i doing wrong ๐ค I am pretty much trying to get the forbidden error to work but it doesn't send the message so um yeah hdsahdhsahdahsd
@bot.event
async def on_command_error(ctx, event, *args, **kwargs):
if isinstance(event, discord.errors.Forbidden):
msg = "The bot requires some of the permissions to execute this command!"
asyncio.create_task(ctx.author.send(msg))
return await ctx.channel.send(msg)
if the error occurs inside your command itself, its wrapped into a commands.CommandInvokeError so retrieving the underlying exception (i.e. Forbidden) requires accessing the .original attribute
- on_command_error doesn't take *args and **kwargs, just ctx and the exception
- why are you using asyncio.create_task? you're already inside an async context
- you gotta access the
originalattribute from the exception. Use something likeexception = getattr(event, "original", event)
ah alr
personally think using create_task ( or swapping the order of sending messages to channel and user ) is better than a direct await ctx.author.send .... the user might have their dms closed.
How is using create task going to change the fact that their DMs are closed?
The error can* be handled the same regardless
it won't block the next line, that's all
as i mentioned in the bracket, or swapping the order...
if you did care about the exception then try/excepting it would be a better idea, to avoid the noise of an uncaught task exception
Yeah ^ I don't think shoving the error into a different context is the best way to ignore it
as for sending both messages at the same time i guess that's fine if you want to do so
How can I except invalid form body?
what are some good coding platforms for a bot? ๐ i use replit but i keep getting rate limit
VSCode, Pycharm, Emacs, Vim
Any webhook's code or bot's code to clear messages of a specific channel?
instantly
how can we use asynchronous functions for dynamic cooldowns? i tried using asyncio.run() too, but it gave me some event loop error
async def nuke_cooldown(ctx):
premium_check = await db.check_premium(ctx.guild.id)
if premium_check == True:
return None
else:
return commands.Cooldown(1, 60)
i am using asyncpg so i must use await for running the check, but then this function is completely non asynchronous and doesnt support asyncio.run
and btw this code is of pycord
!d discord.TextChannel.purge
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") to delete messages even if they are your own. Having [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") is also needed to retrieve message history.
Changed in version 2.0: The `reason` keyword-only parameter was added.
Examples
Deleting botโs messages...
do you have a other script i can use or get?
can someone help me please
are you trying to create a cooldown?
yes
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/cooldown.py at master ยท Pycord-Development/pycord
these exist
just use the decorator
but unfortunately to run an asyncpg command i need to use await and to use await i need to have a asynchronous function which is not possible in dynamic cooldown functions
i tried running my asyncpg command with asyncio.run() too, but that didnt work it gave me event loop errors
i mean you could use a role
for premium and make the bucketype role specific
no i cant, coz i am trying to implement a guild premium membership where all the activation details are stored in a database
probably should
so yes
i think only way to achieve this is by creating a custom cooldown
using cooldownmapping
are those possible in pycord?
but i have problem to get my bot online any help?
should be yeah
yes
did you do what it says?
what?
remove discord.py
i did but still not working
the error?
what is your code?
it says that your app that you are trying make requests to, doesn't exist
Well, I guess a Discord application with such token doesn't exist. Also why would you create a variable DISCORD_TOKEN = ... and then not use it?
well am new to coding and i have used this code befor but the terminal is not working bc when i do "python3 main.py" its not working
and i have only this code that works
What do you mean "the terminal is not working"? It's working perfectly
Did you check that your token inside of the .env file is valid? And for extra sure, you could reset it.
i have reset it today and its the same
So you are sure it's valid?
does this help?
WhAt?
can you print the token passed to the method??
sorry i'm currently going by documentation of the endpoint
i think so
umm yeah now its clear that the token is incorrect
i reset it now but i get the same message
i think if you needed the scope you would get a HTTP 403 code
bro dont say you didnt paste it into your .env file
also how do u have it pasted in ur .env
No
TOKEN="sasdhfajsdf"
Yes
TOKEN=aherguhodfgsdfjgs
yeah...
'DISCORD_TOKEN'='12345465'
like this
i tryd "py main.py" in the terminal and i got this
Well, you've got to install Python before trying to run py
how do i install tho?
The issue here is not your code or anything else, it's you not having it installed.
how do install?
https://www.digitalocean.com/community/tutorials/install-python-windows-10
One Google search away:
How to install Python on windows
like this? pip install python?
Remember that coding a bot is not meant for beginners. The library is made for advanced users, that is explicitly written.
well i like starting hard ๐
Well, maybe install Python before doing anything
wow i cannot believe i walked into this
feel like im say the same thing again, or ask for the same thing again. Please helpe kings and queens
I have also tried removing the curly brackets
well i have that install to my computer but not in vsc
That doesn't change anything?
VSC uses your system installed interpreter or the virtual environment you're currently in
oh ok but the website did not help tbh
Well, you don't have Python installed - which has nothing to do with discord bot development. So it's better using am appropriate channel --> #โ๏ฝhow-to-get-help
Hi guys! Regarding discord bots,
does message.author.id mean the ID of the person who sent the message?
Correct, you can always try it and see
thank you
i haved a bot earlier and then i used python so i have python installd
you saved me from missing a spyxfam ep, ty ๐ซ
whats ur issue tho
wth delete this message
it had ur token
install this library
and then use ```py
import dotenv
dotenv.load_dotenv()
it will load all the environment variables from your .env file in the code
thats a common issue
you should use python -m pip instead of pip
!dashpip
are you on windows?
yea
use py instead of python
which part
the whole process
py -m pip
installing library and calling that function
ywah so now you'll install the library using py -m pip install python-dotenv
other things stay same
may i know whats the name or ur env file?
name is config.env
if its anything other than .env you will ne doing dotenv.load_dotenv("filename")
yeah so instead of filename,you enter config.env there
yes that won't need to provide that argument inside load_dotenv
si senpai
my env file shud use curly brackets or no?
this the template
ENVIRONMENT={dev_or_prod}
BEARER_TOKEN={obtained_from_twitter_api}
USER_ID={user_id_of_burner_twitter_account_which_would_be_following_relevant_people_to_track_their_followers}
DATABASE_URL={postgres_database_connection_url}
TARGET_CHANNEL_ID={channel_id_in_which_you_want_to_periodically_send_messages}
TOKEN={discord_bot_token}
pleasse dont hate me for how dumb I am
and ty for ze patience
no
that worked
It means you aren't allowed to do the action you are doing. We won't help with a boost bot.
why so?
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
what about in dms/
No.
!minusmpip
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.
For windows it's usually just easier to use py -m pip

it worked ya wizard
think i follwed the op correct directions
and the bot is online - its also online in my server but there was a wall of read in the terminal
maybe it hasnt found the data yet?
pip3.10 install discord
bot is online an active in discord channel
but no working

btw in the .env file - shud use @ or no? for username for twitter bot
please dont hate for my plebian ways
you could store this in your code
in a variable
ok will try that - do I include the '@' sign in front of user name or no?
include it
it shouldn't
async def balance(ctx, user: discord.Member):
can 'user' be used for the ctx.author ?
user: discord.Member = commands.Author
this will default the user to ctx.author if no user was provided
oh thanks ! it worked
CODE:
from discord.ext import commands
bot = commands.Bot(command_prefix='.', intents=discord.Intents.all())```
**ERROR I KEEP GETTING**
```AttributeError: module 'discord.ext.commands' has no attribute 'Bot'```
what library are you using? when did you update discord.py for the last time
im kidna new so idk what library you mean but i updated discord.py 10 minutes ago for the 9th time
What command did you use
pip install discord.py
Copy paste it, also are you using a venv?
If you don't know what one is it probably isn't an issue. How are you running python?
When you press the run button, there should be a line in the console that is the actual python invocation
might look like /usr/bin/python3 main.py
Or something like that, do you see it?
will that show in the terminal?
It might, not sure if VSCode displays it or not
Basically I want to make sure your pip and python versions aren't mismatched
if you'd be using a venv, the name of it would show up before the folder 's name in terminal
thats what pops up in the terminal
pip freeze You most likely have a library overriding some things, like having both discord and discord.py installed
ForceSelfBot ๐
discord is just a mirror of discord.py, no?
A mirror package for discord.py. Please install that instead.
There has been other people who had the same error, and they all had discord & discord.py
It got fixed after they uninstalled and re-installed discord.py
Should I try/
oh maybe, never used that package
pip uninstall discord.py right?
pip uninstall discord
Or just pip install discord.py --upgrade
how do i do that
also lookup for forks like pycord, nextcord etc
shouldn't exist
pip freeze into the terminal
Nvm
netcord, wouldn't matter
Disnake is the best
Only extension that should matter would be pycord, disnake, pycord, hakira all use there own
what for dpy 1.7.3
I never installed them
pycord, you can say import discord, but every other such as nextcord it would be import nextcord
thats what i did
nextcord uses discord namespace too
discord.ext.context?
No it doesnt, not from my experience at least
!pypi discord.ext.context
Globally accessable context for discord.py events.
it has both.
Are you sure they arent using import nextcord as discord?
idk what that is lol
my friend told me to install it
I would get rid of it, because your not using it anyways
cus hes python coder
And it might be the offending package
wtf is this
That would be
globally accessibly context ๐ค
no check their GitHub, they use both namespaces
To summarize, pip uninstall discord.py, pip uninstall discord.ext.context then pip install discord.py
we finally have a reply for "how to use ctx in on_message" now
๐ญ ๐ญ
await Bot.get_context(message)
Is that necessary
i can use it in my on ready now ๐๐๐
Just won't always be a valid context
It's the packages name from what the pip freeze says, so yes
Why are you using that in on_ready, Discord.py stated an issue with that
it wont let my bot login so i gotta reset token
It was a joke.
Ah
๐
ah so he is just using an open source project
๐บ I'll make a lib with context for all events and interactions now
Goodluck
Oh yeah, i forgot about my own issue
we can call it RunFunctionCalledContext ez
actually just add it to my python too then i can use it in other projects too
sure omw with my pr to cpython
<3
Im running a file that would run multiple bot instances at once. However im running the code and I come across Missing Acess error, the code runs both bots prefix command perfectly but fails to load the slash commands
That doesn't happen when you run them individually?
No
load as in respond to interaction or registering them?
registering
One bot is the bot that adds every other bot to the database
make sure one instance doesn't override the other...
show code
why 2 instances tho ๐ฟ
I plan on it to be at least way more than 2
why lol
Its the type of bot, So I make private bots for servers known as leagues, each and every bot does the same thing. There is no need for me to create a new file for each
What are you setting it to?
i was copying a youtube tutorial for this
You setting it True or False?
Okay, so why is your dir name something self-bot, and you are also using run(bot=...) I'm assuming False as well...?
There is no reason to do either of this unless you are self-botting
welp, i saw may people using bot=True for no reason at all
^
^
just search for bot=True in this channel itself
@slate swan Send code
im not using bot=True
is it False?
you gotta show ur code if you want proper help man
ik im getting my bot token rn
moderation bot???
Ignoring exception in on_connect
Traceback (most recent call last):
File "/home/mee/rewrite/venv/lib/python3.8/site-packages/discord/client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "/home/me/rewrite/venv/lib/python3.8/site-packages/discord/bot.py", line 1054, in on_connect
await self.sync_commands()
File "/home/mee/rewrite/venv/lib/python3.8/site-packages/discord/bot.py", line 657, in sync_commands
app_cmds = await self.register_commands(
File "/home/mee/rewrite/venv/lib/python3.8/site-packages/discord/bot.py", line 485, in register_commands
prefetched_commands = await self._bot.http.get_guild_commands(self._bot.user.id, guild_id)
File "/home/mee/rewrite/venv/lib/python3.8/site-packages/discord/http.py", line 353, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
@slate swan thats the error
your bot wasn't invited with application commands scope in that particular guild
It was, i thought that was the issue too, I deleted the bot from the database re-added it
nvm i found a solution on github why my bot wouldnt work
well it does say Missing Access with a 403 error code, so its either permissions or scope
i wasnt using bot=True or bot=False
Selfbotting more than likely
whats the correct syntax to enter postgres url in my .env file?
Could it be that it is trying to load both bots slash_commands into 1 guild?
is this correct DATABASE_URL=postgres://XXXXXXX
YOUR_VARIABLE = "THE URL"
Just so you know, you don't seem like you understand what you're doing. When you get banned for selfbotting it will be immediate and span your entire IP. Good luck with your project though
do i need to add https:// or something, please senpai be kind
did you try running those bots one-by-one?
Yes, it runs perfectly
One bot is my actual bot that loads my token, guild id, botid into the database the other is testing
I don't think so, the postgres:// should replace it
thats the issue then, two instances overriding each other

Could i send my code so you can get a better understaning?
do they have same commands by any chance?
postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]
this is the general format
You missed the ql which may be the issue
No, i have a check. If the server id = my operation server it loads a different cog
if var.owner:
Owner.addbot.guild_ids = [var.guild]
bot.add_cog(Owner(bot))
else:
bot.add_cog(Background(bot))
Each bot that i create (private bots), i will have to make a new file. I want 1 file that runs them all with the same code. They each do the same thing
def setup(bot):
var = fetch_client(bot.description)
if var:
commands = dir(Background)
for command in commands:
command = getattr(Background, command)
if hasattr(command, 'description'):
command.guild_ids = [var.guild]
if var.owner:
Owner.addbot.guild_ids = [var.guild]
bot.add_cog(Owner(bot))
else:
bot.add_cog(Background(bot))
This is how the guild id gets selected
ty ty
where do i create this invite link?
I believe it's the OAuth2 > General > Default Authorization ink
yeah i just found it
did not know i had to make a tos
dont even know where to start with that
i don't think this logic is right. var is a guild instance right? so their will always be a var.owner so the Owner cog is always going to be loaded
Thank you so much
Wait so, i am heavily confused what should I be doing then?
is this all on one bot?
if so you can't load cogs per guild. all cogs will be registered to every guild no matter what. what you can do inside the cog is set those commands to one guild using guild_ids=[] so the commands arent regsitered globally
then you can use default_member_permissions=discord.Permissions(administrator=True) so only ppl in ur server with admin perm will see the cmds
why tho?
Its so i wont have to create a new file each time I make the bot
Every bot that gets added is a private bot for another server
that just complicates things and i don't even think that is reliable
they all run the same code
yeah but that won't work
So far it has been aside from the slash commands not loading
yea because u have multiple bots running
I have decided to not do that
I am now running the same file, but different bot instances
well apparently you can run multiple bots in one file lmao.
but again i think you are better off runing different instances
Id prefer running multiple bots, since Im using a command to addthe bot
is this your code?
Also your correct**
because it doesn't do anything other than load a cog
thats part of it. Its way more too it
if var.owner: this will always be executed becuz their is always a guild owner so you will always load the Owner cog
Should I check if the guild.owner is me instead?
wait var isnt a guild instance
def fetch_client(id):
for i in range(0, len(clients)):
if int(clients[i].bot.description) == int(id):
return clients[i]
return None
yeah
ok one second
@slate swan it says client has no attriubte to owner_id
used dir(var)
oh wait
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'bot', 'bot_id', 'guild', 'load_extensions', 'owner', 'start', 'token']
should i do var.guild?
i just did var.guild ot check the guild to see if its my primary server
Same error Missing Acess
yeah because the guild it is trying to load those commands in. The bot doesn't have the correct scope and permissions added to it
One Second I will i reset my database and re-add the bot
but it's multiple bots no?
so yoiu need to readd all of them
with the correct scope and permissions
Not now, Im just testing
@slate swan
Ok so, I just verified and It still returns the error
Earlier a guy said I was overriding it, i have no idea what he meant by that
thats the issue then, two instances overriding each other
What's the problem?
came up with the start of a new bot idea
a mostly social survival game, most commands require someone else from the server to interact in some way. then the results would be something like your friend in the server finds food and can decide whether to eat it all or share it 
then people from other servers can randomly show up and impact your game somehow
how do i trigger something when any exception is raised anywhere while the bot is running even if it's not totally fatal?
@slate swan yo
you can handle exceptions using the on_command_error event
what's the typical way to use some event based messaging in combination with disnake?
say redis/zeromq/rabbitmq
does anyone have code for something that if you do /{cmd} {duration} it will show different embeds if it has a name on it?
hm?
By duration, do you mean the current time ?
"has a name on it"?
you really need to elaborate
also, I don't think you're gonna just get code, we'll help you but you need to do it yourself
fork/3rd party lib moment
?
do you know how i can fix it?
What library are you using?
how do you not know what you installed
Not really idk pycord, try reinviting the bot with the correct scope enabled
"application.commands"
has nothing to do with that-
Pycord automatically tries to sync on connect
but the correct scope isn't enabled here
It prolly uses application commands but he hasn't enabled
Hmmm
So messaging in discord by sending raw network requests from command line against ToS?
if it a user account yes
But if bot account or webhook then not
flags is a string, why would it have a contrast property
Hey @slate swan!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
I always get this error because of help.py
note: I use nextcord
wait nvm
im just dumb
should be str not string
just read the error lol
what's flags?
uh huh so why would flags.contrast be a thing
why are you trying to use flags anyway? This is a slash command, use optional arguments
You aren't parsing that though
..parse the flags..?
Naming a string 'flags' doesn't magically do flag parsing
this is bad design anyway
u either take in a string parse using
regex easiest method
.
flags are ok for text commands, but why would you want this for a slash command
that's just unintuitive af
or yk.. The lib designed for this argparse
Stop what you're trying to do with flags. Use optional arguments
like the ones you already have? User and flags
mhm
Yes
u could even use the discord commands.Converter to create a neat custom convertor
cool but not relevant-
channel is not what you think it is
maybe yk, figure out what channel is
bruh that's a completely different function
Why are you using after.channel everywhere, but just channel in that line
probably
what am i supposed to do with this
i read it
Fix your code lol
:/
did you read the relevant part? https://discordpy.readthedocs.io/en/latest/migrating.html#command-extension-changes
yes that's exactly where the problem is
like this?
in python, if you declare a variable of the same name twice in the same scope, the second definition overwrites the first
i need to put it in one?
L5345
i am a newbie man
it's recommended to know atleast basic python before using discord.py
What do you think this will do?
def foo():
print('a')
def foo():
print('b')
foo()```
print nothing?
I alr said
error
Please learn python first
what is channelID and voiceID supposed to be
The what channel
Text channel? Voice channel?
your variable and column names are really confusing
voice, channel, interface
???
might wanna fix up those names so anyone looking at your code doesn't spend all their time figuring out names
likee createdtext, createdvc, jointocreatevc
And most importantly yourself, maybe that's why you have this issue in the first place
Everywhere
Your variables, db
this is why we name things properly
what part of "flags is a string, why would it have a contrast property" do you not understand?
Is there a way to get the original bot role
maybe you mixed spaces and tabs
the role that gets created upon bot joining the guild?
!d discord.Role.is_bot_managed
is_bot_managed()```
[`bool`](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)"): Whether the role is associated with a bot.
New in version 1.6.
!d discord.Guild.self_role
property self_role```
Gets the role associated with this clientโs user, if any.
New in version 1.6.
Ah didn't know about that
Tnx
Hello so Iโm coding something where you have 2 users answering in 2 different modals. Is it possible to add both the results into 1 embed?
!code share code blocks instead
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
Any guide tfor ban and kick commands?
Like @unkempt canyon has.
!ban @somone 2hr he is bad guy duh
I also want the staff using only {prefix}mute and {prefix}ban command. I don't want them to give the permission of kick and ban in guild. Like ban\mute others indirectly.
Hello so Iโm coding something where you have 2 users answering in 2 different modals. Is it possible to add both the results into 1 embed?
well why wouldnt you be able to do that
you can check for specific user ids if thats what you want
or maybe roles, there are a lot ways to do it
Im trying with a db but AttributeError: 'Bot' object has no attribute 'db'
You can use typehints
Many people don't wanna open photos
Well, you will need to access your database through your database connection, and not your bot instance I would say๐ค
Anyone know how to list subcommands of a hybrid_group in discord.py 2.0?
property commands```
A unique set of commands without aliases that are registered.
yeah, its not a list but a set
thank you
Yes I was thinking that too
Oki
If you would go for user ids, the best you could do is storing them in a database, and removing/adding them everytime something changes. Then just well yes, check if they're in the database inside the specific command (you could also make a separate function for that).
right
so ive added user ids to a database but when i try to send the ids it sends as "(713579531935416331,)" , why?
Those are tuples, get the valid index - t[0]
How much does aws cost after free trial?
a lot
Talk in numbers
anyone know
That question was answered
id suggest using oracle instead
its cheaper + lasts longer
!pastebin
Pasting large amounts of 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 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.
I literally replied.....
Maybe read duh
If you don't read answers don't expect others to help you later on 
createdvc is he ID of the interface channel, and not the one owned by the user
Well the voice channel you're creating afterwards
In the code you showed you only create two channels, interface and "Join to Create"
Somewhere you create a channel with the user's name
ID of that channel should be saved in the DB as createdvc
Right, so output.id you need to save it in the DB somewhere, and then use that ID when selecting to change the channel's name in callback
Well, I'd rename the field to interfaceid and not createdvc
And then here, you replace createdvc with output.id
Keep this like that
But rename the column from createdvc to interfaceid
Since you store the interface channel ID
Then in here, you add a new SQL query to store output.id in createdvc column
You'll need a interfaceid and createdvc column
Yeah that's fine
Nah output.id is not defined there
You need to set to something like 0
Then when you create a voice channel, it will be saved
In that part you only save the interfaceid and jointocreatevc
Then in here you save the createdvc
Yeah you need to set a default value for createdvc in the database settings, can be something like 0
Anyone got any good resources / videos for creating buttons?
async def button(ctx):
button = discord.ui.Button(style = discord.ButtonStyle.primary, label="Add a label")
are you using any library in particular?
does anyone have a good idea for measuring time between interactions with buttons? (user specific)
!d discord.Interaction.created_at ig?
property created_at```
When the interaction was created.
you can subtract 2 datetimes to get a timedelta
Need to be able to get and restore a yes / no button response from a user
Thank you!
You can put 0
Or just go in the settings of the table
You can set a default value for a column
Default/Expression I suppose or Default at the bottom right
Never used that interface
i'm making a bot i've run out of ideas ๐
Try a api wrapper ๐
๐
is it possible to run a same bot with two diffferent codes?
like executing two with same bot token
sure
what are the cons?
That's what happens when people forget to shut down one instance of the bot and then wonder why it's replying twice 
ye
Well it's not really useful, just make one so that you know where things are
The main con is that it's not handy to get an overview of your code if some things are in one file and others are in another and you run them separately.
And can lead to your bot replying twice if you've done it incorrectly
i m doing something bad tho... i dont know "js" and im thinking to copy paste someone's code and i dont know how to combite it with py
i know you shouldnt copy paste
oh yeah
Don't copy paste, instead try to understand the code they made and convert it yourself in Python
I dont know js
Then try to think about how the command can be done in python
wouldn't having two scripts using the same token also lead to an easier hit of a "429 too many requests"?
Use the command you want to have and then think about how a Python implementation can be done
oh okay
Depends what you do, but yes
im curious how people combie different languages together in one folder to run their bot
They are mostly extensions for something else
oh
Like writing a game in C++ as an extension and then using in a discord bot which is written in python
ye
Hello, I am getting this error while trying to run commands on my bot. Anybody know the fix / issue?
is yr file named OpenAi? The file where u r importing
If yes, change the name of the file to something else
Yes
Change the name
that doesnt fix it
yep looks right
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Remove createdvc from your query
Remove 0 as well
anyone here experienced with mongodb?
No that was correct before
Please just ask your question. Don't ask to ask, ask for topic experts or DMs. Skip the formalities and ask away and ask in #databases
What you need is a new statement to insert the createdvc in the database
lmao
Yeah thay was correct
After output = ... you make a new query and get output.id in the createdvc column
Imma watch a movie 
Are there any legal ways to create music bot?
Since many famous bots were banned who used youtube api
That doesn't UPDATE, that's a SELECT - check some documentation to see how to update data
Get a legal contract that allows you to use their service for a music bot.
that wont happen
sad
@slate swan deservers @copper yarrows role. my guy helping people day and night without any break

whoops... pinged someone
Kind of made a break of helping here and came back at helping here again
โค๏ธ
its a user
Looks like role pings are off.. thank goodness
Nop
lmfao
@feral timber always pulls that lmao (sorry not sorry ping)
<@&267627879762755584>
@sick birch is pinging me
right back at you buckaroo
In all seriousness though I didn't know you can mention but not ping. That's quite interesting
when it is connected how can i disconnect it without closing the script
Would be nice to have some UI option to do that as well
logout?
!d discord.Client.close
await close()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Closes the connection to Discord.
If you don't have perms it won't ping that's just it - but you can mention like any role with <@&id>
Your script won't close but the bot will go offline
thanks
op here it is
Not able to sorry
I only do it with the ones that I don't have permission to ping
I don't actually know if you can turn off role pings like you can with users
I think that'd be a cool feature, exactly like how you can disable reply pings
fwiw the second nested try/except isn't necessary
stop with the shenanigans, shenanigans
NEVER!
is this a code related issue?
yes
only thing i think of is that ctx isnt there so it has no context to send so it errors?
Oh this isn't discord.py
Not sure if I can help then, sorry.
I mean I'd prefer to make the buttons in discord.py
If you point on me on the right path perhaps
It might as well be a library error since these 3rd party component libraries aren't built very well
yea i'd rather stick to one library
is there a way to do it in discord.py?
of course
https://github.com/Rapptz/discord.py/blob/master/examples/views/counter.py here's a pretty easy example
there are more in that same folder
Do you have a slash command named channel
regulars right now: ๐ฆ
thanks
looks a bit confusing tbh
At first yeah, spend some time getting to know how it works and it'll get easier ๐
perms
await channel.set_permissions(guild.default_role, overwrite = None)
await channel.set_permissions(guild.default_role, view_channel = True)
this one resets all the permissions for the @ everyone role.
exactly
yw
the insert happens properly but when i check the table associated instead of the whitelist_roles having the role id it just contains {}
@inviteblocker.command(description='Manage the inviteblocker whitelist')
async def whitelist(self, ctx, action: Option(str, 'Whether to add or remove a role from the whitelist', choices=['add', 'remove'], required=True), role: Option(discord.Role, 'The role you want to add / remove from the whitelist', required=True)):
await ctx.defer()
check = await db.run_query(f'select exists(select * from inviteblocker where guild_id = {ctx.guild.id})')
if check[0]['exists'] == True:
await db.run_query("update inviteblocker set whitelist_roles = whitelist_roles || '{{}}'".format(role.id))
ibwembed = discord.Embed(description='The role has been added to the whitelist successfully', colour=discord.Colour.green())
await ctx.respond(embed=ibwembed)
else:
ibwembed = discord.Embed(description="Couldn't set the whitelist role since inviteblocker is current disabled.\nEnable it by using **/inviteblocker toggle**", colour=discord.Colour.red())
await ctx.respond(embed=ibwembed)
can someone help please
i am using postgres with asyncpg and the discord lib is pycord
Give me a second to look at your code
What Are you using to make the db connection?
Also for the record I'm not sure what one would expect from table inviteblocker; .... Is that the same as SELECT * from inviteblocker; ???
await db.run_query("UPDATE inviteblocker SET whitelist_roles = $1 WHERE guild_id = $2, role.id, guild.id)
yes it is
alr
Depends if you have auto commit enabled 
Assuming alr supports it, use it to parameterise your SQL. Don't use f-string.
And honestly, using a sub-query to find out if the entry exists feels wrong. Perhaps there's some Postgres optimisation, but unless you have a very specific need, just select count(*), or better select for update in a transaction
i figured it out
all i had to do was a bit of concatenation or whatever they call it:
await db.run_query('update inviteblocker set whitelist_roles = whitelist_roles || '+"'{"+str(role.id)+"}'")
That is bad
Use the parameterisation
Don't use f-strings, or concatination.
So something like this:
db.run_query('update inviteblocker set whitelist_roles = whitelist_roles || {?}', str(role.id))
But this assumes that "alr" supports this kind of thing. It it does not, you don't want to use it.
@slate swan perhaps ask your question a a free channel?
hey need some help
how do i get the
this thing on my discord bot
Just like you do now
Simply send a message like
> A message
ty
I donโt know why but Iโm having this sudden urge to watch yt tutorials just to see how awful they are
mmh?
If you need to find a bot for a specific purpose I recommend you to search on the internet, you will find lots of them.
im running a loop to check a json file i have, but i get the error Error checking user: 'data' at every loop. does anyone know what this means?
Well that's just your opinion buddy
You're late to the party buddy
Anyone know how I'd format a command like !slowmode 1h30m20s (h = hour, m = minutes, s = seconds)
@willow sky
Yes?
whats up
uh what kind? and why me..?
because you are a good person
Message me in dm
u could split it in strings
but idk if it's the best solution, not quite efficient
Well you could go with this horrible regex
!e
import re
r = "[0-9]+[hmsd]"
t = "1h30m20s"
print(re.findall(r, t))
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
['1h', '30m', '20s']
cc @latent ocean if you haven't found a good way until now.
Maybe not the best but might be worth the try as it works and can be easily parsed. I used to use that regex before. Otherwise there probably are some libraries around you can search for.
!pypi durations-nlp
!pip time-str or this
(Sadly) libraries for everything these days
the point of libraries is so that you dont have to do it all yourself
which saves time
Correct me if I'm wrong, never said the opposite
Imagine
import autocode
autocode.maek("free bobux generator")```
I wonder what would copilot give if you entered "free bobux generator" prompt
When the you have so many packages that you get dependencies conflicts
Timedelta converter is fun to make by yourself imho
stops giving output after that
try creating a function named free_bobux_generator

future of ai

Where can I learn how to make a discord currency bot? with slash commands, using pycord, and using sqlite3
The documentation of relevant libraries along with brainstorming how it can be done

Can I get a sample code of a currency bot, made using pycord?
you're basically being asked to read the docs and begin with it
That's not how you will learn
Internet is your friend though
what
use brain
Source code: Lib/sqlite3/
SQLite is a C library that provides a lightweight disk-based database that doesnโt require a separate server process and allows accessing the database using a nonstandard variant of the SQL query language. Some applications can use SQLite for internal data storage. Itโs also possible to prototype an application using SQLite and then port the code to a larger database such as PostgreSQL or Oracle.
The sqlite3 module was written by Gerhard Hรคring. It provides an SQL interface compliant with the DB-API 2.0 specification described by PEP 249, and requires SQLite 3.7.15 or newer.
This document includes four main sections:
Think about how you would save the data, etc.
The documentation helps you get it solved
I'd rather use aiosqlite though
I will use mysql
Everything, think about how you can make commands based on how you need them
you'll first need to learn how create a bot instance and running it
there's a guide in the docs iirc
yeah an async driver would be better forsure
^
You won't have code to copy pasta, you will need to be creative and think about how to do it yourself.
That will get you a base bot ^^
To make economy commands, you will need to use your brain and think more about it 
In other words: use your brain
its all about how you implement your idea to bot using docs
it teaches you how to make a bot
integrating the bot with a database and making an economy system would be your brain job
Think about how you can use database to make currency commands etc.
Learn basic python, then implement your idea
You will need to brainstorm how these functions can be done and then implement them by yourself
dw just go sleep ๐
wut
lmao
lmao
Deleting everything
cringe
sussy
We won't forget you @slate swan no worries 

make some rpg game
else games tho I hate games
make a discord fork
lmao
@bot.slash_command(name="register")
async def register(ctx):
db = sqlite3.connect("userinfo.db")
cursor = db.cursor()
cursor.execute("INSERT INTO userinfo(userid, balance) VALUES(?,?)", (ctx.author.id, 0))
db.commit()
db.close()
await ctx.respond("Registered!")
is it like this?
make a chat group or chatting platform ig
no yes, noone can tell without complete code
kinda yeah
wdym by kinda yeah
that like 4 lines of code there is useless which u will have ti repeat every command with economy stuff
ok
Try it and see 
We're not interpreters
oh wait... i forgot to create a database ๐
imagine imagining
am sitting on the last seat so noone cares
noice
ok now i created the database
@bot.slash_command(name="register")
async def register(ctx):
db = sqlite3.connect("userinfo.db")
cursor = db.cursor()
cursor.execute("INSERT INTO userinfo(userid, balance) VALUES(?,?)", (ctx.author.id, 0))
db.commit()
db.close()
await ctx.respond("Registered!")
@bot.slash_command(name="bal")
async def balance(ctx):
db = sqlite3.connect("userinfo.db")
cursor = db.cursor()
await ctx.respond(cusor.execute("SELECT * FROM userid WHERE balance=?", (balance,)))
db.commit()
db.close()
is this correct now?
why don't u run and see
# Mute user
time.sleep(duration)
# Unmute user

for i in range(duration):
await asyncio.sleep(1)


How do i wait for response in slash commands? for pycord
wait_for
ok thanks
is it possible to convert message.content.lower into slash commands?
Absolutely useless as you have parameters but sure
Ah you mean a message to a slash command, no
Make the slash commands correctly and how they are meant to be done
sO iF the User TypE like THis
for input in option of slash command, will it work?
Yeah you said it wrongly above, you can lower that in the code, yes
Would be arg.lower()
where would i put that?
In your slash command code
!d discord.StageChannel.members
property members```
Returns all members that are currently inside this voice channel.
check if the member object is in the return value @slate swan
Learn all about Slash Commands and how to implement them into your Discord Bot with Pycord!
thanks
You should use an asynchronous SQLite library like aiosqlite or something
is this possible?
@bot.slash_command(name"testcommand", description="Test")
async def test(ctx):
#if user respond = hi
await ctx.respond("hello")
#if user respond = test
await ctx.respond("test")
something like this is possible?
Just saying
Also you should only connect to the database once in the start up of the bot
ok
!d discord.ext.commands.Bot.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
wait for "message"
async def test(ctx:discord.ext.commands.Bot.wait_for):
Maybe you want to learn python, at least the basics, before doing a bot
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
maybe
or you can ask asher to code for u, he's a nice person
Why?
sqlite doesnt have connection pools
they actually mean having a single connection throughout the bot ig
cool? thats exactly what they said
yeah and that explains the "why", creating connections inside the commands may cause multiple connections writing in the file at the same time, since sqlite databases are just files and not actual database servers
..and whats wrong with multiple connections?
theres even a feature to assist with concurrent operations, https://www.sqlite.org/wal.html
Heres an example of why not to use a shared connection/cursor https://gist.github.com/sgtlaggy/9d43d5223314d559792ea6544673f1da
you might face database locked errors?
just use asyncpg make life easier
could have simply used 2 different cursors
Does anyone have a discord bot code? For reaction roles i can read and learn? Im using replit (python)
You're just one google search away to finding that
class Memebut(discord.ui.View):
def __init__(self , msg):
super().__init__(timeout=60.0)
self.value = None
self.msg = msg
@discord.ui.button(label="Meme", style=discord.ButtonStyle.blurple)
async def Next(self, interaction: discord.Interaction,button: discord.ui.Button):
r = requests.get("https://meme-api.herokuapp.com/gimme")
data = r.json()
embed = discord.Embed(title=data["title"], color=discord.Color.blurple())
embed.set_image(url=data["url"])
await self.msg.edit(embed=embed)
await interaction.response.send_message("wtfshrike", ephemeral=True)
@discord.ui.button(label="Stop",style=discord.ButtonStyle.red,emoji="๐ฅ") # or .danger
async def stop(self,interaction:discord.Interaction,button:discord.ui.Button):
return await interaction.response.send_message("Stopped",ephemeral=True)```
@commands.hybrid_command(
name="meme",
description="Get a random meme from reddit.",)
@checks.not_blacklisted()
async def meme(self, context: Context) -> None:
req = requests.get("https://meme-api.herokuapp.com/gimme")
embed = discord.Embed(color=discord.Color.blue())
embed.set_image(url=req.json()["url"])
embed.set_footer(text=f"Requested by {context.author.name}" , icon_url=context.author.avatar)
msg = await context.send(embed=embed)
view = Memebut(msg)
await msg.edit(view=view)
how to disable the buttons
as i presss the stop button
requests
for child in self.children:
child.disabled = True
# edit the message with new view
import discord
import os
client = discord.Client()
@client.event
async def on_read():
print("We have logged in as {0.user}".format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startwith("!hello"):
await message.channel.send("Whats good!")
client.run(os.environ('TOKEN'))
just started making a bot, this comes up with an error when i run it (im using replit)
Traceback (most recent call last):
File "main.py", line 4, in <module>
client = discord.Client()
TypeError: __init__() missing 1 required keyword-only argument: 'intents'
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot 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
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
Is the client.user part normal?
misspelled on_ready
Yeah that seems normal, though I'd rather use message.author.bot to ignore bots
oops
ive added this code and same error
In that case you haven't added it properly.
bot = commands.Bot(command_prefix="!", intents=intents)
For you it will be needed in discord.Client(intents=intents)
Finally fixed the error and moving on to the next one
Best feeling of coding
How would I get the author of a messageโs id?
m = channel.fetch_message(id)
m.author
What if i dont have have message id
How would I get the author of a messageโs id?
That implies you have the ID
I mean how do i get the id of soemoen who posted a msg
???





