#discord-bots
1 messages · Page 215 of 1
Yes
I did see the /add command from my main file
@app_commands.command(name="setrole")
@app_commands.describe(
role="Pass the role to give after verification here."
)
async def setrole(self, interaction: discord.Interaction, role: discord.Role):
c.execute("INSERT OR REPLACE INTO roless (server_id, role_id) VALUES (?, ?)",
(interaction.guild.id, role.id))
conn.commit()
embed = discord.Embed(title="Role Successfully Set", description=f"I suggest you to make sure that {role.mention} can't access your verify channel once the role is given.", color=0x2B2D31)
await interaction.response.send_message(embed=embed)
@naive briar ^
aiohttp unclosed connection when have session.close where it should be
Im trying to delete a dropdown once interacting with it. Not sure what to do as await interaction.message.delete() doesnt work. Here is my code:
View:
class InviterView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.add_item(Inviter())
Dropdown:
class Inviter(discord.ui.Select):
def __init__(self):
options=[
IGNORE THIS
]
super().__init__(placeholder="What game are you playing?", options=options, min_values=1, max_values=1)
async def callback(self, interaction: discord.Interaction):
rant = random.randint(0, 0xffffff)
value=rant
channel = vini.get_channel(1085711629775294516)
userss = len(interaction.user.voice.channel.members)
usersize = await interaction.user.voice.channel.create_invite()
embed = discord.Embed(title=f"Need More People!",colour=value, description=f'To invite others to your voice channel simply go to [#1085711668622921988](/guild/267624335836053506/channel/1085711668622921988/)`. \n \n :point_right: [Click this link to join this parties voice channel.]({usersize}) :point_left: \n \n')
embed.set_author(name=f"{self.values[0]} LFG", icon_url=vini.user.avatar.url)
embed.add_field(name=":loud_sound: Voice Channel",value=interaction.user.voice.channel.name, inline=True)
embed.add_field(name=":map: Game",value=f'{self.values[0]}', inline=True)
embed.add_field(name=":family_mwgb: VC Size",value=f'{userss}/10', inline=True)
embed.set_footer(text=f'Requested by {interaction.user} | {interaction.message.guild.name}', icon_url=interaction.user.avatar.url)
await interaction.response.send_message(f"Your invite has been created at [#1085711629775294516](/guild/267624335836053506/channel/1085711629775294516/)", ephemeral=True, delete_after=3)
await channel.send(embed=embed, view=Close(interaction.user))
I don’t think self.stop() will remove the drop down but will make it so that no one can interact anymore
So, how would I remove the drop down?
edit the message and set view to None
that works, but it doesnt remove the embed with it.
if you want to remove everything then just delete the message..
to delete it after user interacted you can use delete_after=2
where?
wouldnt that just delete it after 2 seconds
no matter if its interacted or not
I want it to be automated to where its deleted after the dropdown has been interacted.
do it in the select's callback then
Hello
Does anyone know how to reference a .ui file for custom QListWidget list item ?
how to make on_message(message) read only from certain channels?
so if i have to run my bot on docker container, where can i host it, im new to this.
Check if message.channel.id is the id of channel you want to respond in
#user-interfaces not discord bots related question
Oh from scratch? Well you will need like a hundred (or several hundred) nvidia A100's to train the neural network to start with
Fr
On VPS
i might have commited a troller
na im looking for a completely free service as my bot doesnt require much
but that's an interesting perspective
You could actually deploy it to some kubernetes cluster, might be cheaper, but if you have persistent data stored on drive VPS is better. VPS is better generally, it's not much more expensive
Free tier VPS
Oracle, amazon aws, microsoft azure
Is it possible to have wait_for message event inside a button view which outside a cog
I wonder how can I get self.bot.wait_for
!d discord.Interaction.client
property client```
The client that is handling this interaction.
Note that [`AutoShardedClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AutoShardedClient "discord.AutoShardedClient"), [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot"), and [`AutoShardedBot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.AutoShardedBot "discord.ext.commands.AutoShardedBot") are all subclasses of client.
or, subclass View and take the bot instance in the _init_
And use inter.client.wait_for?
Not quite
Depending on your implementation the callback can be implemented as a method in your class or you can set some attribute of view and get it after view.wait()
can i use the on_message event for responses ?
what do you mean by responses?
interaction.response.send_message
like if a bot sent a message by an interaction response , will the other bot who has on_message work with it ?
if the response is not ephemeral, yes
when i use a bot do demo somthing. is that sent to the channel instantly? and what if you need to correct something. how is that done so that the posted ouitput is replaced with the new run?
okay thanks
sup
why does python hate me
Time to move to rust 🦀
Rust will hate him more 💀
Wdym?
hi let's say hypothetically i am running my discord bot on another PC. what's the best way to make it auto re-deploy (after syncing up) everytime there is a push to the github? docker? 👁️
Well, I would suggest docker for hosting a bot, but not sure how you would do that. I bet @feral timber would know.
Maybe smth with workflows or smth? Idk what they rlly are.

lmfao
Docker
You’d need access to your server to tell it to pull the new container though.
Easiest way is probably a single file Flask server with one route that just calls into Docker
Whenever there is a docker question, just know ima ping u.
😄
I'm not very familiar with docker, do you have any good source where i can learn its basics and what to do to achieve what i'm trying to
Ur the only person I know who is good at docker 🤷♂️
I literally suck at Docker
Nah. Ur better than nedbat, so u are good 🙂
Um... I'm actually not sure
I can get you the Docker tutorial, but I don't know of anything Discord bot specific for Docker
Wait then who was the dude who was rlly good at docker. I was like 96.3% sure it was you.
Uh... now I can't find what I was looking for -- This looks even more thorough though: https://docker-curriculum.com/
I'm telling Ned!!
ty
did you mean the getting started page?
https://docs.docker.com/get-started/
ive used the docker documentation as my starting point and found it fairly difficult to piece it together since the information is scattered everywhere on their website, but i did eventually get a basic understanding of docker and docker-compose
THERE WE GO
ty ty
Google results kept re-routing me to Docker's main site asking me to make an account
Hi @feral timber
What brings you to my abode today?
Docker, apparently
The oops is strong in this here young cadet
For once
Code: https://paste.pythondiscord.com/execagovaf
Issue: The paginator is not suceeding
what do you mean it's not succeeding
the paginator is not sent
probably because you are doing followup.send with the paginator
whats the solution
only send one of them
huh
make your own paginator so you actually get to know whats happening in the code, the lib's code doesnt look too perfect
it committed pycache to git bruh
the documentation doesn't follow a fixed style too, and the typing isn't alright either
Is there a way to make a discord bot that has two way communication with an external program? I made a tampermonkey program that sends messages to a discord channel if you type in a message box that gets appended to every website you to to, essentially works the same as a keylogger (but not malicious at all it’s a message box that they click send to send the keystrokes when they want so it’s a message communication system)
But this sends it through a webhook which cannot read messages and can only send them. So I was wondering how to make it so that I can send a message in that server and then my message will appear on my friends screen by sending my message content from the discord channel to his computer but without him having discord open.
Essentially I’m asking how to make something like a two way webhook communication
the issue is with the defer
its hard to deal with this without followup.send
!pypi reactionmenu
A library to create a discord.py 2.0+ paginator. Supports pagination with buttons, reactions, and category selection using selects.
I said the issue is with the defer
async def cog_command_error(self, ctx, error):
if isinstance(error, commands.BadArgument):
embed = discord.Embed(title=':x: Event Error', colour=0xe74c3c) # Red
embed.add_field(name='Event', value=error)
embed.description = '``py\n%s\n``' % traceback.format_exc()
embed.timestamp = datetime.datetime.utcnow()
await self.bot.send(embed=embed)
Error is that it doesnt send this embed...
In terminal it logs the error but that too is not in this format or any format
atleast send the error for an reference
there's nothing like self.bot.send .... it would be ctx.send
i did ctx.send and it still doesnt send
did you add the @Cog.listener decorator
When i do this :
Running background task...
raise TypeError(no_bot_cog.format(base, elem))
TypeError: Commands or listeners must not start with cog_ or bot_ (in method mod.cog_command_error)
The above exception was the direct cause of the following exception:
just make a discord bot with websockets
there is a good async websocket library
Is there an article on that
licence version pyversions tests docs openssf websockets is a library for building WebSocket servers and clients in Python with a focus on correctness, simplicity, robustness, and performance. Buil...
I know nothing about websockets lol
you could use websockets, but there is something called message brokers..
which establishes two way communications via messages, perfect for what you want, look into rabbitmq, not websockets
it's just a two-way connection
It’s javacript code that gets auto injected to website consoles upon load
So that’ll work?
if the tampermonkey script has network access i assume it will be sending it from the host's computer
so yes
and the discord bot will obviously be hosted on a vps or another computer
Yea
It’s so that me and my friend can communicate in school cause it’s a school chromebook
makes sense
Welp looks like I have a lot to read up on about websockets
web sockets will be a hell to manage for this, please look into message queues/brokers
why so
i've built a two-way websocket chat in only 50 lines before
it's not anything harder than rabbitmq
that's completely irrelevant
web sockets and message queues work at different layers
it's the same principle
no, its not
When I search up websockets tutorial on YouTube tho all the videos are like 3 hours long
Is it hard for someone to learn who has no knowledge on http connections
Besides webhooks
a message queue is like an interface that different clients and backends sends messages to regardless without having to know who the receiver is, that way you can establish a two way communication between multiple clients fairly easy, with web sockets you would be having to write all the handlers and listeners and you'd also need to know who the receivers are
the receiver is simply a discord bot, it can still manage multiple clients
no, the receivers are the clients in the browsers
Mb my friend took my phone and sent u a friend request
and the bot
the discord bot is receiving messages from the browser clients
and vice versa, hence two way communication.
yeah
although doable with web sockets, message queues will remove a ton of headache
The receiver is supposed to be my friends computer, no?
you simply spin up a rmq instance on the server the bot runs on, and all clients simply consume the messages from the rmq, quite that simple
I thought Tampermonkeys supposed to fetch it somehow
i can't imagine it would be any easier
yeah, this is event driven, e.g a message is sent and the bot or the browser client picks it up, this is where message queues comes in
you're re-inventing the wheel of a message broker if you go down the route with bare web sockets
this is what a message broker does for you
what is even the benefit here
that you don't have to rewrite your own message broker with bare web sockets
why would i
that's literally what you're suggesting them
here, even a simpler yt video https://www.youtube.com/watch?v=jbPUnANkh0o @shut briar
Learn how you easy can build your own reciver async by using Python3
i will in this video help you to understand how to recive your messegt from the queue and convert your binary string to json data.
just send the author name and message content from the browser to the bot
the bot will re-send it as a webhook
and take in messages to send back
you're only thinking of the contents being sent, and not how it's handled and by whom its handled
that's literally what message brokers are for
What is a message broker? A message broker is software that enables applications, systems, and services to communicate with each other and exchange information. The message broker does this by translating messages between formal messaging protocols.
it generally uses web sockets under the hood
wait yeah it's a method you dont need that,
if you use ctx.send does it not send the error message at all?
that can describe every transfer protocol in existence
"a software that enables applications to communicate with each other"
it's the same idea
A message broker is an architectural pattern for message validation, transformation, and routing. It mediates communication among applications[vague], minimizing the mutual awareness that applications should have of each other in order to be able to exchange messages, effectively implementing decoupling.[4]
well with that said, everyone would be driving the same car regardless if they're a racer or a taxi
a websocket with proper auth would be more than enough for the purpose, using rabbitmq seems a bit excessive
whats faster / easier / more efficient / easier to learn for a beginner
i honestly disagree
but sure, web sockets works as i said earlier
you just get to deal with.. well... web sockets..
rabbitmq wraps websockets internally
websockets are faster but it also depends on your implementation
that's what im saying
it's nothing more than a chat with a username and message
Why do my buttons stop working after around 15 minutes?
!d discord.ui.View Views have timeouts, they will stop working if you don't pass the timeout as None
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
would something like this work?
class BuyTicketButton(discord.ui.Button, timeout = None):
you need to pass it to View, not the Button
is there a better way to communicate between two different computers using tampermonkey, or is using a discord bot the way to go
worth pointing out that no matter what you choose, both solutions require a webserver that your tampermonkey script and discord bot can use to share messages, and that raises the complexity much more than having a webhook provided by discord's servers
so would something like this work?
view = discord.ui.View(*, timeout = None)
the websocket server can be hosted alongside the bot
still means you're opening it to the web
alright thank you i will go and test it now
if you also want your view to work after a restart, you'll need Client.add_view() to add the view during startup
https://github.com/Rapptz/discord.py/blob/master/examples/views/persistent.py
oh so u cant just communicate directly between two computers without having a website??
or can it communicate directly through tampermonkey somehow..
website and websocket servers are unrelated
oh so tampermonkey can do it all?
import asyncio
import websockets
async def echo(websocket):
async for message in websocket:
await websocket.send(message)
async def main():
async with websockets.serve(echo, "localhost", 8765):
await asyncio.Future() # run forever
asyncio.run(main())
here is the simplest websocket server
tampermonkey is not the server, the computer running your discord bot is
what's tampermonkey?
a user script thing
injects javascript code into websites as soon as you load it up
userscripts
wow that sounds useful, but you dont actually need it here
instead of opening console and typing code up, auto inject
you could just give your friend an .html file to open
and that html file will run javascript that will communicate with your websocket server
i dont have a server idk how that works
the websockets library handles the server part for you
you simply have to run it with your computer
u can open it on a chromebook?
no, the chromebook is the client
i mean .html
yeah
any browser~
any browser can open html files
why not
sorry if im naive but im tryna learn everyone starts somewhere yk
you can, but the issue is maintaining a connection to the other person, which gets into peer-to-peer concepts that's out of my knowledge; when you have a server with a commonly-known IP address / URL, its easy for everyone to connect there, and thats basically what discord is
and also a server can handle multiple clients at once
without having to discover them yourself
So i add that in the on_ready function? How do i specify Which button? Or do i just add that and it Will always make every single button usable again?
setup_hook like the example shows is fine, and it applies to every button contained within the view you give it
@commands.Cog.listener()
async def on_message(self, message):
ctx = await self.bot.get_context(message)
if message.author.bot: return
data = await self.bot.db.fetch('SELECT * FROM afk WHERE author = $1', message.author.id)
if data:
timestamp = data[0][2]
time = humanize.precisedelta(timestamp - discord.utils.utcnow().timestamp(), format='%0.f')
await self.bot.db.execute('DELETE FROM afk WHERE author = $1', message.author.id)
await ctx.success(f'Welcome back, you were away for **{time}**')
if message.mentions:
for mention in message.mentions:
data = await self.bot.db.fetch('SELECT * FROM afk WHERE author = $1', mention.id)
if data and mention.id != message.author.id:
timestamp = data[0][2]
time = humanize.precisedelta(timestamp - discord.utils.utcnow().timestamp(), format='%0.f')
await ctx.success(f'**{mention}** is currently **AFK**: {data[0][1]} - {time} ago')
For some reason my afk event isn't working anymore (ever since i switched to a different vps)
This is what it puts out when i do ,afk and then type or get mentioned.
No traceback
is it the time that's wrong?
yeah
are you sure you don't have any duplicate rows?
it's supposed to be liek this
yeah im sure because it always worked until today when i switched to a new vps
and all of a sudden it broke
what VPS are you using
One my friend is providing me
almost at 7000 lines of code for my bot 
He has a vps providing service lol
anyone have ideas for general server features or pvp minigames
but this shouldn't be a problem since it's just like any other vps
The vps is running on ubuntu 20.04
How's your infrastructure look like?
At a certain size for my projects I focus on setting up robust infrastructure, then continue making more features
right now the bot isnt getting as many servers as i'd like and it was just essentially one in depth game before
and a pretty anti-social game which probably doesn't encourage server owners to keep it
also, idk what you mean by infrastructure, organization or efficiency?
All of that, continous integration, deployment pipelines
That sort of thing
And a robust codebase, too.
I find that many times people get really carried away by just adding new commands and features but never really stop to think about the "behind the scenes" stuff
It's almost like building a really beautiful frontend website, but have a crappy backend API to run the whole thing
at the same time doing that prematurely can also get you stuck without making any actual features
it's hard to imagine even with my crappy coding that will become much of an issue
Right. That's why I mentioned "at a certain size"
Some people like to do all of this at the start, but if you're not one of those people you would just wait until you project crosses the certain threshold and then start worrying about it
by the time my bot would use enough resources for that to become an issue i would have patreons supporting my ability to get better aws hardware
Just food for though, really. You don't have to
or cloud whatever
i try to think about it but ultimately it seems better to focus on performance as that issue comes up
This is a realisation I came to myself quite recently. I've been trying to do a better job of setting up a nice codebase for myself to work off of.
I am currently working on a bot that's at a few hundred lines of code so far and only 3 commands 
I personally find that to be the hard part :P
my new bot only has a tag system and it's probably around 700 lines
You can always add new features or commands to your bot - that isn't really all that difficult nor important
Having a bot with 1000+ lines for just /ping is pretty normal 
It is important if you're middling under 1k servers tho
nvm it's 807
Or at least improving features if it's possible
I would argue good code organization and infrastructure is always important
How can I remove a user from a list I created
Or all of the above 
You have to make a good sandwich that people want to buy before you start figuring out how to efficiently mass produce it
Cause when I do ticketer_list.remove(ctx.author.id) it says like ctx is not defined
That got me confused
But I guess also don't make a sandwich in a way that's impossible to mass produce later
You don't have to start immediately selling the sandwich first :P
You can hold off until you can efficiently mass produce, then go public
personally for me readable and reusable
Pretty much the same concept
I mean lines go pretty fast.
But the opposite is also common
It has it's own name
"MVP" for minimum viable product
I think that's just personal preference really
it's impossible to finish that way
pls tell me the 7k lines are in the same file
my logic when starting a project is to get something usable out first
No I went to the other extreme and have 31 files
what does your file structure look like?
!e print(7000/31)
@cloud dawn :white_check_mark: Your 3.11 eval job has completed with return code 0.
225.80645161290323
can you use tree command @dull terrace ?
I am intrigued rn
do tree /F to show files in win
Wow, 3 entire lines of code
Alright prepare to cringe
How can I remove a user from a list I created
Cause when I do ticketer_list.remove(ctx.author.id) it says like ctx is not defined That got me confused
I mean 3+ does scale pretty high.
The error is pretty much telling you exactly what's wrong, send the code where you're trying to do it so we can help you find a solution
Organization🗿
Not the entire file~
Just the command/event/function that is throwing the error.
Idk about clean it's pretty chaotic
And the error traceback itself preferably.
Im trying to delete a dropdown once interacting with it. Not sure what to do as await interaction.message.delete() doesnt work as it comes back with a 404 error. Here is my code:
View:
class InviterView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.add_item(Inviter())
Dropdown:
class Inviter(discord.ui.Select):
def __init__(self):
options=[
IGNORE THIS
]
super().__init__(placeholder="What game are you playing?", options=options, min_values=1, max_values=1)
async def callback(self, interaction: discord.Interaction):
rant = random.randint(0, 0xffffff)
value=rant
channel = vini.get_channel(1085711629775294516)
userss = len(interaction.user.voice.channel.members)
usersize = await interaction.user.voice.channel.create_invite()
embed = discord.Embed(title=f"Need More People!",colour=value, description=f'To invite others to your voice channel simply go to [#1085711668622921988](/guild/267624335836053506/channel/1085711668622921988/)`. \n \n :point_right: [Click this link to join this parties voice channel.]({usersize}) :point_left: \n \n')
embed.set_author(name=f"{self.values[0]} LFG", icon_url=vini.user.avatar.url)
embed.add_field(name=":loud_sound: Voice Channel",value=interaction.user.voice.channel.name, inline=True)
embed.add_field(name=":map: Game",value=f'{self.values[0]}', inline=True)
embed.add_field(name=":family_mwgb: VC Size",value=f'{userss}/10', inline=True)
embed.set_footer(text=f'Requested by {interaction.user} | {interaction.message.guild.name}', icon_url=interaction.user.avatar.url)
await interaction.response.send_message(f"Your invite has been created at [#1085711629775294516](/guild/267624335836053506/channel/1085711629775294516/)", ephemeral=True, delete_after=3)
await channel.send(embed=embed, view=Close(interaction.user))
to delete dropdown you edit message and set view to None
you said you want to remove dropdown
did you use what i sent yesterday?
Yeah, didnt work.
Sorry, im trying to delete both. The embed and the dropdown with it after interacting.
have you tried self.view.remove_item(self)
In the same place as the view?
just do await message.edit(embed=None, view=None)
in the dropdown
let me try this one rq
Ima try it in like 5 minutes. Just need to do something real quick. Thanks for the help.
what you said yesterday and today are different
you wanted to remove the dropdown but now you want to remove the dropdown and the embed
I initially just said dropdown because whenever I try to delete a button it deletes both the button and embed. I assumed it was the same with dropdowns.
that shouldn't happen...
if I were to delete the view it deletes just the button but If I did interaction.message.delete it deletes the whole thing.
a view can hold any number of select menus (dropdowns) and buttons
and a message can hold multiple embeds and one view
I was able to fix it though, I did:
await interaction.response.defer()
await interaction.delete_original_response()
I dont know, just always did it with me.
that's just deleting the whole message though
not only the embed and view
thats all they have in the message tho
honestly no point in deleting the message when its ephemeral
https://paste.pythondiscord.com/afucazezat
imo these two classes seem really redundant
is there a way to put them into just one?
Why does my bot say interaction failed after like 1min if you haven’t interacted with it
because it times out
Is there a way to not time it out?
I mean reaction roles buttons doesn’t time out
what are you referring to
try this
Kk
Let me wait -_- lol
can someone please help me figure out the problem
i made a custom reload command but it keeps returning a new embed with more cogs on it: ```py
@commands.command(
name = "reload",
aliases = ["rl", "rload"]
)
async def reload(self, ctx):
if ctx.author.id == 1069789232824058016:
errors = 0
cogs = []
for c in list(self.bot.extensions):
try:
self.bot.reload_extension(c)
cog = c.replace("cogs.", '')
ax = cogs.append(f"{utils.success} Reloaded {cog}.py - 0 Errors")
except Exception as e:
cogs.append(f"{utils.failure} **Failure Loading {cog}.py - {e}")
if cogs:
embed = discord.Embed(
description = "\n".join(cogs),
color = utils.green)
await ctx.send(embed=embed, mention_author=False)
yes, you should go to your main.py file and import the button class that you are trying to sync, and you go to your on_connect, and do (classname).start()
this will create a feature to not time out or get failures on buttons if you restart the bot or it gets timed-out
either both ways work and its efficient
you realize this is a python server, right
what
there is no View.start or Button.start method
you can sync your buttons like that so it wont timeout aswell, i did it with my ticket system
what library
i dont use any library for it other than discord's regular library, it works for me like that
yeah
because that function does not exist
oh wait no its self.add_view(classname())
then you import the button class
i really dont under stand anything about coding i just looked up coding servers so i can find someone to help me change discord bot's status to online
we can only help with python here
@smoky sinew should i just return it instead of sending it?
So I dont understand how the tree forms..
(someone provided)/(you created) an invalid package.json file
for more help you can get help in discord.gg/djs
I have a problem with my modmail bot, im not quite sure to understand what seems to be the problem.
Bug: user dms the bot, create a ticket successfully but they doesn’t receive the moderator’s responses in dms.
Way to solve: If another user opens a ticket, both tickets will now be receiving the moderator’s response somehow.
And yes, I do get errors. Although, I do not understand what is wrong in my code.
https://paste.pythondiscord.com/afucazezat
imo these two classes seem really redundant
is there a way to put them into just one?
i wouldn't recommend so
they serve different purposes
but like they have virtually the exact same structure
Take strings as arguments and use it in the class
Did u review the basics like we suggested?
Yeah I quite understand more now
I managed to do my list thing
Without asking help and even looking on internet
There’s some terms I still don’t understand (that’s obvious) but yeah
Ask about them
Id rather help you figure it out, then write it for you.
Whats the error.
I have a problem with my modmail bot, im not quite sure to understand what seems to be the problem.
Bug: user dms the bot, create a ticket successfully but they doesn’t receive the moderator’s responses in dms.
Way to solve: If another user opens a ticket, both tickets will now be receiving the moderator’s response somehow.
And yes, I do get errors. Although, I do not understand what is wrong in my code.
Imma send the error 2 secs
@gusty flax Traceback (most recent call last):
File "C:\Users\matis\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "c:\Users\matis\Desktop\ModMail GIE\main.py", line 183, in on_message
await user.send(embed=embed_reply)
^^^^^^^^^^^
do you need my script too?
Whats the error message?
Obviously it stems from sending the embed 😅
what's the error message though
Wats the error.
But that’s not always, only happens sometimes
oh oups lol -^^ [2023-03-16 20:24:35] [ERROR ] discord.client: Ignoring exception in on_message
Thats not the error message.
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
TypeError: can only concatenate str (not "int") to str```This is the error message of that traceback.
ouf sorry -- UnboundLocalError: cannot access local variable 'embed_reply' where it is not associated with a value
this?
Yes 😄 but pls send ur whole error.
Lmao alright
indent your await user.send(embed=embed_reply) line
[2023-03-16 20:46:49] [ERROR ] discord.client: Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\matis\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "c:\Users\matis\Desktop\ModMail GIE\main.py", line 183, in on_message
await user.send(embed=embed_reply)
^^^^^^^^^^^
UnboundLocalError: cannot access local variable 'embed_reply' where it is not associated with a value
yes that is what we need. and send ur code too pls
Wait, they sent the code?
alright yeah ive heard python requires a good indentation in order to work, will try it. ty
^ It is how scoping works 😄
I dont understand why it works sometimes and other times it doesn't tho
because in your case indenting will create a new scope
or technically not
i think the else part is just not running
where do you want me to intend it tho? it keeps giving me red lines everywhere
but if statements do not create scope
just indent it by one tab or 4 spaces
Gives me a red line tho
R u indenting the right amount?
what does that mean
Send ur whole script. I dont see it. @smoky sinew
remove the extra space before await
There’s no extra space
yes there is
Ur indenting is messsed up.
look closely
Embed_reply is too far forward
notice how these don't align
I think they need to move the embed stuff back
the await is fine where it is.
Want me to send updated script?
Push ur embed_reply lines to the right.
There we go!
yup
where do I ask about python database in a discord bot?
ok i posted it there
Code: https://paste.pythondiscord.com/alecazequj
Error: https://paste.pythondiscord.com/etizolubiq
Extra Info: When I remove any of the value in view, it says a parameter is missing and when I readd it, it says got multiple values
Just create your own paginator
Whatever library you're using looks like it's poorly written

i am honestly suprised that #discord-bots gets a reply faster then #databases does
my issue is part of the discord bot but the prob rests in the database
so sadly I have to post in the other channel
async def load_extensions():
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
await bot.load_extension(f"cogs.{filename[:-3]}")
@bot.event
async def on_ready():
print("Ready")
what's wrong with this? the cogs not loaded
you never call the function for run it.
@bot.event
async def on_ready():
print("Ready")
await load_extensions
??
Learn about various components of async programming with a practical example.
Do you know what coroutine functions are
Or just functions in general
not really, I'm new in coding
hello! im new to py and looking forward to make a discord bot using it. Anyone there to guide me pls
You have to call the coroutine function (async function) for it to return a coroutine then await the coroutine
Any way to move threads between Forum Channels or Change the perms of the individual thread?
Or I have to do something like save the entire message history and create a new thread and send it there?
!timeout
Are you comfortable with python basics?
not yet im totally new
Ah i see
I would recommend learning the basics first since discord bots are complex and you'll have a hard time making them
There are lots of free courses and books available
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
this is py discord
ohk
ty sir
Code: https://paste.pythondiscord.com/makuhamele
Issue: Current page is the first page but Previous button is not disabled, Current page is the last page but Next button is not disabled.
@unkempt mauve perhaps see this for reference. Not a ready solution for dpy but something that can be used as an example https://github.com/BobuxBot/BobuxAdmin/blob/master/utils/pagination.py
pagination is fine
I am talking about buttons
your code is complexed
Lines 25-27 for max page formula, 49 and 57 for next/prev buttons callbacks
It's "complex" because of typehints I presume 😀
Other than that it's pretty clean
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 490, in _run_event
await coro(*args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem_Test\bot.py", line 311, in on_application_command_error
raise error
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 890, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\cooldowns\cooldown.py", line 93, in inner
result = await func(*args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\server_moderation\cog.py", line 119, in edit_channel
await inter.response.send_message(view=ChannelSlowmode())
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\interactions.py", line 880, in send_message
payload["components"] = view.to_components()
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\view.py", line 204, in to_components
children = [item.to_component_dict() for item in group]
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\view.py", line 204, in <listcomp>
children = [item.to_component_dict() for item in group]
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\select\base.py", line 194, in to_component_dict
return self._underlying.to_dict()
"options": [op.to_dict() for op in self.options],
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\components.py", line 295, in <listcomp>
"options": [op.to_dict() for op in self.options],
AttributeError: 'str' object has no attribute 'to_dict'```
class ChannelSlowmode(nextcord.ui.View):
def __init__(self):
super().__init__()
@nextcord.ui.string_select(placeholder="Please select a slowmode delay", max_values=1, options=["30 secound", "1 minute", "5 minutes", "10 minutes", "15 minutes", "30 minutes", "1 hour", "2 hours", "4 hours", "6 hours", "8 hours", "16 hours", "24 hours"])
async def on_select(self, select: nextcord.ui.StringSelect, inter: nextcord.Interaction):
await inter.channel.edit(slowmode_delay=select.value)
await self.message.edit(content="HI")```
Options should be instances of SelectOption shouldn't they
!d nextcord.ui.string_select
nextcord.ui.string_select(*, placeholder=None, custom_id=..., min_values=1, max_values=1, options=..., disabled=False, row=None)```
A decorator that attaches a string select menu to a component.
There is an alias for this function called `select`.
The function being decorated should have three parameters, `self` representing the [`ui.View`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.ui.View "nextcord.ui.View"), the [`ui.StringSelect`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.ui.StringSelect "nextcord.ui.StringSelect") being pressed and the [`Interaction`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Interaction "nextcord.Interaction") you receive.
In order to get the selected items that the user has chosen within the callback use [`StringSelect.values`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.ui.StringSelect.values "nextcord.ui.StringSelect.values").
it is
In your case they clearly are strings
options = [nextcord.SelectOption(label="30 Secouds", value=30),
nextcord.SelectOption(label="1 Minute", value=60),
nextcord.SelectOption(label="5 Minutes", value=300),
nextcord.SelectOption(label="10 Minutes", value=600),
nextcord.SelectOption(label="15 Minutes", value=900),
nextcord.SelectOption(label="30 Minutes", value=1800),
nextcord.SelectOption(label="1 Hour", value=3600),
nextcord.SelectOption(label="2 Hours", value=7200),
nextcord.SelectOption(label="4 Hours", value=14400),
nextcord.SelectOption(label="6 Hours", value=21600),
nextcord.SelectOption(label="8 Hours", value=28800),
nextcord.SelectOption(label="16 Hours", value=57600),
nextcord.SelectOption(label="24 Hours", value=86400)] ```
@vale wing
Oh hell why not use time conversion
xD
oh gosh
Anyways if you want to do it like this:
options = {
"1 minute": 60,
"5 minutes": 300
}
actual_options = [SelectOption(label=k, value=v) for k, v in options.items()]```
Make a simple View pagination ig 🗿
but this is not about my error
can we continue with the error?
Solved
You need to parse actual_options to options in decorator
Whats wrong at my options?
They are strings
options=["op1", "op2", ...]```
This is what is incorrect
Yeah, it is an nextcord.ui.string_select
||nextcord|| 👀
How can i make a followup empfemeral?
https://paste.pythondiscord.com/ezuqipumev
the callback function is not working
Do you know how views work
Simply because it doesn't exist
Just take a look at code I sent, you saw typehints or that formula and decided it's too complex to understand prob
Actually if you parse embeds to pages the code simplifies even more
Max page will be len(pages) - 1
Entries are not needed at all
hello, can someone send me a embed generator for python without cogs? I'm trying it for like 2 hour and nothing works? PLZ (under embed generator I mean like a dropbox where you click you choose name, description, color and you can add fields and then the bot will send it)
Cogs are merely a way of organising code (and dynamic updates) just telling
What
He means embed constructor I believe
I know, I only said without cogs bc I dont have cogs in my code now, but I will add it if its going to be easier
the button does exists dude.
discord.ui.View.callback does not
Mm about embed constructor, do you want to implement that on discord?
so what do I do
yeah, I creating a discord bot and I really wanna do it
Read the docs
I provided a good example
You need to assign a callback to the buttons
Oh, what exactly are you struggling with
!d discord.ui.Button.callback
await callback(interaction)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The callback associated with this UI item.
This can be overridden by subclasses.
I do have a callback function bruh
You have callback method in your View subclass, it will never be invoked by internals
everything😂
at first I was going in a good way but now, I'am just really tired
I dont even know what is python😄
at this point
That thing is pretty complex
If you really don't know python that would turn into spoonfeeding
I didn't mean it that way, I meant that I'am tired, and bc of im tired I dont really know anything
Ah then you might want to have some rest
Anyways I can help with UX design
So you understand what you actually need to do
Basically a view with buttons like "Set Title", "Set Color", "Set Description", "Add Field" and so on, on button click a modal pops up, then you fetch data user provided and go on with embed construction
For this concrete situation modals callbacks implementation sucks
It sucks generally
But it's easy to fix that thing by adding a future attribute
self._fut = asyncio.create_future()```
Setting result in callback
```py
self._fut.set_result("whatever")
self.inter = received_inter```
And creating some wait method
```py
await self._fut
return self.inter```
@discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.
The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View"), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") you receive and the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button "discord.ui.Button") being pressed.
Note
Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button "discord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
I need the buttons to be disabled according to the page dude
What's the problem
;-;
Do disabled = True
button.disabled=True and edit embed or msg
with view=self (assuming it's a class)
And actually your left button should be always disabled from start
So simply pass, disabled=True on button deco
how do I undisable it later lmao
And then edit the buttons according to the pages
if I do @discord.ui.button(label='Previous', disabled=True) it will be always disabled if I am not wrong
It will be disabled from the start
Then when user clicks the button, then on the callback do button.disabled=False and edit the embed with view=self
So you can enable it again
the callback requires discord.ui.Button right
Wdym?
@discord.ui.button(....)
async def somename(self, .....):
#this is the button callback
how can user click on a disabled button
Sorry mb, re-ebable it when people clicks the right button
self.somename.disabled=False
Some name is the callback name
o
if I get back to the first page, I will make a if condition where the button will be disabled right
Yeah
if ....==1:
disable it and edit the embed
same for the next but reverse
Then also do
if .... == len(a_list_of_embeds):
disable the right button
hm
Yeah u got it
nah bro. I am just dumb. my brain is less functioning because of insomnia
I am too bad at understanding stuffs lol
Oh sed

I have a simple example actually
Which is made with dpy
But actually u can copy paste it to ur code, thats why i can't give it lol. (Spoon feeding uk) xd
I have a package for disnake that handles pagination logic
if you're interested you can take this as example https://github.com/Snipy7374/disnake-ext-paginator though it's for disnake
what's the best way to store user items for a small bot, json file with a dictionnary in it ? or smth else ?
sqlite
I meant small bot, just to use with a small group of people, no need for a huge db 😄
it's not huge
that's why it's named lite
They didn't recommend cassandra did they :p
cassandra 💀
Bro plans on making discord sized bot
pickle it
u making a paginator?
yes and everything is solved
alr was bout recommind mine https://github.com/TheWever/dpy-toolbox/blob/main/examples/paginator.py
its shit but works xD
U made that to work?
yes 
Now the issue is the next button is not disabled when the pagination has only one page
Do this
button(disabled=current_page==len(some_list))
This will return True if the current page is equal to the list and will return false if current page is not equal
I did it in other way
if len(self.pages) == 1:
self.next_page.disabled = True
await self.message.edit(view=self)```
I know it takes a few nanoseconds
I mean if u wanna disable it from the start if the list has 1 embeds and page is also 1
The way u r doing is you need to atleast interact the buttons in order to disable it🗿
nope
it disables itself
just takes a few nanoseconds
Ugh ig u r doing outside the callback then i assume?
@discord.ui.button(label='Next', style=discord.ButtonStyle.green, disabled=len(self.pages) == 1)```
I try to do this but vsc says self is not defined nor pages is but it is defined above
Yeah it isnt
how do i insert pages there then
Btw u can do pages=self.pages too xd
Outside the init func
It will be a global var for the class then
Tho i think the way u r doing is good too
Lol
have an update() function that disables the buttons
see what i did in my paginator
All bros suggesting their paginators 😔😔
While i dont have mine to suggest
ok i just updated it
something's wrong with intellij
discord version?
!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.
2.2.2
can someone explain how to properly version something to me 
why 2.2.2 not 2.22 or 2.3

what does that mean
i think they mean upload a file
i use semver except i start the version as 0.0.0
instead of 0.1.0
if you're using disnake you do it like this
then you can do
if file.content_type == "image/png":```
to check if it's a type
what ab d.py
ah
nvm
just typehint it as attachment
iirc you can't edit ephemeral messages?
sorry if its dumb, I'm not that good programming. I'm trying to make my bot work on slash commands (not hybrid, only slash) but every time i search i find a different thing and when i try it, it tells me I'm incorrect in one way or another. I've searched a lot and some say to import something called discord_slash that i cant find anywhere, others to import something called interactions, others say to do a @client.tree.command that i do not understand and other things tell me to do cogs first and I'm really lost.
whats the "easiest" current method to do this?-
are you using normal discord.py?
yes
thanks, ill take a look at it
@stone gate here are the docs for a normal slash command https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.command
just add that decorator to your function
and your function takes in an interaction object instead of context
so for example, if my code is this:
async def get_sheet(ctx):
# Load credentials from json file
scope = ['https://www.googleapis.com/auth/drive']
creds = Credentials.from_service_account_file('credentials.json', scopes=scope)
gc = gspread.authorize(creds)
sheet = gc.open('SHEET').worksheet('Sheet1')
data = sheet.get_all_values()
response = discord.Embed(title="Sheet Content", color=0x00ff00)
for row in data:
response.add_field(name=row[0], value='\n'.join(row[1:]), inline=False)
await ctx.send(embed=response)```
i just would need to change the @client.command to `@discord.app_commands.command(name="Get Sheet", description="Retrieves the Sheet Data")`
and the `async def get_sheet(ctx):` to `async def get_sheet(interaction)`
name can't have spaces
like that?
or capital letters i think
@discord.app.commands.get_sheet
replace this with @discord.app_commands.command
and you still need to remove all the places you use ctx
hybrid commands 😎
if you're not using any cogs then just do @client.tree.command()
for the record ctx or interaction are fine
are awful; you get both the downsides of message and slash commands with hardly any benefits
as long as you use it throughout
so the await cxt.send(embed=response) should be noe something like interaction.send(embed=response)
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
interactions have responses that they have to send
you must send one and you can only send one
huh
I don't have problems with hybrid commands
so, something like send_message(embed=response)
maybe it's that I got used to them
you can't use any modals or anything like that or send ephemeral messages
await interaction.response.send_message(embed=embed)
bwuh, what a problem
thanks! i think im understanding now
yeah it is lol
yes you need a prefix command to sync your slash commands
well if it is then sure
@client.command()
async def sync(ctx):
await client.tree.sync()
@stone gate something like this
aight
and run it every time you add/delete commands, or update command info
either the bot does not sync or the command isnt working '. .)
oh i get this
NameError: name 'client' is not defined```
i think they still take a while to update sometimes
did you use bot or client
wdym?;;;
should be a line similar to client = commands.InteractionBot() near the top of your main file
it's probably bot or client if you're following tutorials
and this is above?
not above everything
Hey, im having trouble with my discord.py bot. I want to make it change statues every 5 secs but for some reason it doesnt work. Its an error on line 11 and the error says this: Traceback (most recent call last): File "c:\Users\adenk\Downloads\xero\xero.py", line 11, in <module> async def change_status(): File "C:\Users\adenk\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\tasks\__init__.py", line 816, in decorator return Loop[LF]( File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2800.0_x64__qbz5n2kfra8p0\lib\typing.py", line 957, in __call__ result = self.__origin__(*args, **kwargs) File "C:\Users\adenk\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\tasks\__init__.py", line 172, in __init__ self.change_interval(seconds=seconds, minutes=minutes, hours=hours, time=time) File "C:\Users\adenk\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\tasks\__init__.py", line 742, in change_interval sleep = seconds + (minutes * 60.0) + (hours * 3600.0) TypeError: can only concatenate str (not "float") to str
i don't understand how it can be undefined unless it's in another file
oh wait yeah that might be it
do i need to define it in every file or just the bot.py file?
in that case move it to the same file or from that file, at the top import client from <file_name>
@iron turret your seconds are a string instead of an integer
also do not change every 5 seconds that's an easy way to get ratelimited
although that's probably going to make a circular import
you mentioned the wrong person lmao
you're doing maths with a string
discord is
because a string was passed
oh i see
like this¿
you're supposed to press the save button and send the link, don't send a screenshot
it should change upon saving
sorry myb
send the other files too
aight
since you are loading extensions no need to add commands too
it's because you are using client in the commands file
i guess
Why'd you add 2 commands separately? I mean technically it is okay but what is the point
i was just following what google said ;;w;;
have you heard of cogs or extensions? @stone gate
class CalculatorCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@app_commands.command()
async def calculate(self, interaction):
...
await client.add_cog(CalculatorCog(client))
use this approach along with extensions instead of using import
wait i dont fully understand
https://discordpy.readthedocs.io/en/latest/ext/commands/extensions.html
https://discordpy.readthedocs.io/en/latest/ext/commands/cogs.html
extensions are just different files the bot can load, and cogs can hold multiple commands events and loops
so, i should move both get_sheet and calculate to a cog? how do i do that? should i move them to another file or just classify them as cogs?
it depends on what the commands do
if they are small you could probably just fit everything into the main file
without using cogs/extensions at all
so this is what my directory looks like
inside of commands i obviusly have calculate.py and get_sheet.py
okay so, if im understanding correcly, what we're doing here is
Create a cog named CalculatorCog
adding the "calculate" command into the cog
and finally adding the cog
i dont know the specific terms for those actions, but im able to read it that way
you don't even need to make a cog if you only have two commands just move them to the main bot.py file
oh ill have more commands soon
i just want to first understand how to do slash commands first before moving on
it's basically an organizational tool
what you've got already works if you move it into the same file where you define client
yeah, i just want everything to be more organized and accesible, if i just add everything to the main file itll eventually be a mess to edit commands and find everything i need
ill try understanding this and reading the documentation to see if im able to figure it out
thanks for the help!
how can I add option_enums to discord_slash api for discord bot
isn't discord_slash super outdated?
i don't think there's such thing as option enums, it's just an autocomplete
in discord.py it's as simple as using Choices
i found out how to
also they aint that outdated
yes it is
does it even still work with discord.py
you know discord.py has its own slash command system
why don't you just use that..
discord_slash was literally created late 2021
because discord.py was slow with updates
how do i set up a cog?
why?
Im using this setup_hook thing that i was following from the tutorial i was seeing but the console gives me an error asking me to setup the cog, and it just gets weirder the more i try to solve the problem
why don't you put the commands together if you have two commands
because i intend on doing a lot more, i just want to understand first how the slash commands worked so i can make the rest
i dont want to make everything and then break it all trying to make the cogs and slash commands work
sorry if it just seems like im being stubborn
you don't even need cogs though
so should i just write everything on the main file? wouldnt that get messy really fast?
i mean it depends on how big your bot is and how you want to organize it
cogs are usually used alongside extensions but you shouldn't make a new file for each new command
i see
extensions? i only use cogs
why?
everyone sets their bot up differently, but i have my main, settings, .env and then a cog_extension folder and divided up my cogs based on the event listeners that are used. except commands and slash commands have their own file
cause im still a newb? idk
so you are using extensions
if you use load_extension anywhere in your code then you are using extensions
they are different from cogs but an extension can have any number of cogs in it (or could have none at all)
sorry for the inconvinience, im really bad at understanding stuff just from the get-go, and my english isnt that good to understand well the documentation. Im more of a "i see an example that applies to my case and understands the patterns of it"
what is your bot like?
like, what does it do?
yeah
Basically i have this google sheets calculator for roleplay to calculate stuff like battles, buying stuff, inventory and things like that. I want the bot to automate the process (interact with data given by the users and feed it/modify a sheet inside the calculator) so that i dont need to do everything manually
so you are using a command to edit the google sheet?
how many commands do you expect to have?
i would use cogs/extensions if you have any other commands that aren't related to google sheets, maybe have a google sheets extension
hmmmm, let me see, like around 20?
it shouldn't be a problem to put them in one extension or the main file if they're all for the same purpose
i see
do you need me to explain how cogs / extensions work?
https://paste.pythondiscord.com/epadocisoz heres how i did it
looks pretty good, though i wouldn't make a separate extension for each command
then you will have 20+ files
i mean, yeah, i would like to at least have my commands on a separate file-
you've done pretty well with the extension stuff, i would add a cog like this:
import gspread
from google.oauth2.service_account import Credentials
import discord
from discord.ext import commands
class CalculationCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
self.creds = Credentials.from_service_account_file('credentials.json', scopes=self.scope)
self.client_gs = gspread.authorize(self.creds)
self.sheet = self.client_gs.open("Lyrical DMG").worksheet("Calc") # Replace with your spreadsheet name and worksheet name
@commands.command()
async def calculate(self, ctx, var1: str, var2: str):
# Update spreadsheet with new values
sheet.update_cell(3, 1, var1) # Update cell A3 with var1
sheet.update_cell(3, 7, var2) # Update cell G3 with var2
result = sheet.acell('C4').value
dmg_type = sheet.acell('D3').value
attacker = sheet.acell('C3').value
defender = sheet.acell('E3').value
crit_chance = sheet.acell('F13').value
crit_multiplier = sheet.acell('F16').value
crit_damage = sheet.acell('E14').value
response = discord.Embed(title="Calculator Result", color=0x00ff00)
response.add_field(name="Daño Total", value=result)
response.add_field(name="Tipo de Daño", value=dmg_type)
response.add_field(name="Critico", value=crit_chance)
response.add_field(name="Atacante", value=attacker, inline=True)
response.add_field(name="Defensor", value=defender, inline=True)
response.add_field(name="Roll de Crit", value=crit_multiplier)
response.add_field(name="Roll Necesario", value=crit_damage)
await ctx.send(embed=response)
def setup(bot):
bot.add_cog(CalculationCog(bot)) # adds the calculate command too
but replace sheet with self.sheet
well actually mos of the documented stuff was wrong and a friend that knows how the google API works helped me make it work lmao
wdym the documented stuff was wrong?
commented* those were lines/stuff he fixed
ah i see
How do i write a command that takes an arbitrary number of arguments
can i just *arg?
what if i want it to gather all of the args of a certain type? Wasn't there a thing for that?
greedy?
!d discord.ext.commands.Greedy
class discord.ext.commands.Greedy```
A special converter that greedily consumes arguments until it can’t. As a consequence of this behaviour, most input errors are silently discarded, since it is used as an indicator of when to stop parsing.
When a parser error is met the greedy converter stops converting, undoes the internal string parsing routine, and continues parsing regularly.
For example, in the following code:
```py
@commands.command()
async def test(ctx, numbers: Greedy[int], reason: str):
await ctx.send("numbers: {}, reason: {}".format(numbers, reason))
``` An invocation of `[p]test 1 2 3 4 5 6 hello` would pass `numbers` with `[1, 2, 3, 4, 5, 6]` and `reason` with `hello`...
ah that would be it. Vaguely remembered something about that
okay so now, what should i add on my main file?
What if I wanted something custom for this? for example strings that begin with letter "a"
hmm, i would guess create your own converter extending greedy
i don't think you can do that with the default one
okidoke, sounds good
if you haven't already, load the extension by doing await client.load_extension("filename") replacing the slashes in the file name with dots
like you would with a python import
actually i think you might be able to do Greedy[CustomConverter] instead of extending it
i will double check @full lily
so if the file is calculate.py on the commands folder, what should that look like?
await client.load_extension("calculate")
or
await client.load_extension("commands.calculate")
the second one
await client.load_extension("commands.calculate")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: 'await' outside function```
try this
@client.event
async def setup_hook():
await client.load_extension("commands.calculate")
what is it
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/gspread/client.py", line 150, in open
properties = finditem(
File "/home/container/.local/lib/python3.10/site-packages/gspread/utils.py", line 133, in finditem
return next(item for item in seq if func(item))
StopIteration
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 947, in _load_from_module_spec
await setup(self)
File "/home/container/commands/calculate.py", line 40, in setup
bot.add_cog(CalculationCog(bot)) # adds the calculate command too
File "/home/container/commands/calculate.py", line 13, in __init__
self.sheet = self.client_gs.open("Path to Victory").worksheet("info") # Replace with your spreadsheet name and worksheet name
File "/home/container/.local/lib/python3.10/site-packages/gspread/client.py", line 160, in open
raise SpreadsheetNotFound
gspread.exceptions.SpreadsheetNotFound
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/bot.py", line 29, in <module>
client.run(im censoring this)
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 860, in run
asyncio.run(runner())
File "/usr/local/lib/python3.10/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/usr/local/lib/python3.10/asyncio/base_events.py", line 646, in run_until_complete
return future.result()
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 849, in runner
await self.start(token, reconnect=reconnect)
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 777, in start
await self.login(token)
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 621, in login
await self.setup_hook()
File "/home/container/bot.py", line 14, in setup_hook
await client.load_extension("commands.calculate")
File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1013, in load_extension
await self._load_from_module_spec(spec, name)
File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 952, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'commands.calculate' raised an error: SpreadsheetNotFound: ```
i think its an API thing though, let me check
Hey @stone gate! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discord.com/developers/applications
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
LMAO I FORGOT
bot.add_cog(CalculationCog(bot)) # adds the calculate command too
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 947, in _load_from_module_spec
await setup(self)
TypeError: object NoneType can't be used in 'await' expression
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/bot.py", line 29, in <module>
client.run('censoring my token')
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 860, in run
asyncio.run(runner())
File "/usr/local/lib/python3.10/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/usr/local/lib/python3.10/asyncio/base_events.py", line 646, in run_until_complete
return future.result()
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 849, in runner
await self.start(token, reconnect=reconnect)
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 777, in start
await self.login(token)
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 621, in login
await self.setup_hook()
File "/home/container/bot.py", line 14, in setup_hook
await client.load_extension("commands.calculate")
File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1013, in load_extension
await self._load_from_module_spec(spec, name)
File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 952, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'commands.calculate' raised an error: TypeError: object NoneType can't be used in 'await' expression```
what does your code look like?
did you await Bot.add_cog?
also did you reset your token
nope, the await is on the "await ctx.send" just before
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.
bot.add_cog(CalculationCog(bot)) ```
the setup function should be async
oh that's my fault
and you need to await the add_cog
i forgot to put that
bot.add_cog
capitalize Cog
yeeeahhh it works
@full lily yeah you can do this apparently:
class CustomConverter(commands.Converter):
async def convert(self, ctx, argument):
if not argument.startswith("abc"):
raise BadArgument("The argument does not start with abc")
else:
return argument
@bot.command()
async def command(ctx, argument: Greedy[CustomConverter]):
...
np
now i get this error when using the !calculate command:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'sheet' is not defined```
replace everything named sheet with self.sheet
thanks
now, with that out of the way, how did the slash commands were made again? Lmao
this guide explains it well ^
@smoky sinew one last question, if for example, different commands use different sheets, instead of self.sheet shouldnt i do something like
damage.sheet
money.sheet
character.sheet
and define each one?
or is it better to do a different cog per sheet?
just make a separate variable for each one
Ok so @smoky sinew do you remember this problem of yesterday when members doesn’t receive moderator’s response but when I open a ticket, the interaction bot-user restart?
@gusty flax do you? Cause even after correcting my script with you guys, its still lagging without sending an error code
huh
The thing we thought we fixed
With my intends
Well it didnt work
This is when opening a ticket by myself, everything stop lagging =
If others want to help me :
I have a problem with my modmail bot, im not quite sure to understand what seems to be the problem.
Bug: user dms the bot, create a ticket successfully but they doesn’t receive the moderator’s responses in dms.
Way to solve: If another user opens a ticket, both tickets will now be receiving the moderator’s response somehow.
And no, I do not get errors. I do not understand what is wrong in my code.
yup
Alright
Can you give my 5-10 mins? I need to get on my pc
I can't access message content in my new bot, i have that intent on but still it won't give me anything. Did discord really pulled the plug on it??
you need to enable the intent in your code too
!intents
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
You need to always wait for mod's messages
!d discord.Client.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.11)"). 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.11)") 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.11)") 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**...
And combining it with while True:
...
You can make it easily
I think you should make a global variable too where it breaks the loop
I'll never understand why people use while loops with wait_for
ask your question, someone will answer it eventually
Don't ask to ask
garlic today
putt party is better
💀
So this is my code to transfer users that have a specific role to another role
It's not working
!code pls share in form of text instead of pictures
why are you even calling __eq__ manually
your error is that arg1 is a string and you're passing a string to join
'''@client.command(pass_context=True)
async def moveusers(ctx, arg1, arg2):
server = ctx.message.guild
role_name = (' '.join(arg1))
role_id1 = server.roles[0]
role_id2 = server.roles[0]
for role in server.roles:
if arg1.eq(role.name):
role_id1 = role
break
if(arg2.eq(role.name)):
role_id2 = role
break
else:
await ctx.send("Role doesn't exist")
return
for member in server.members:
print(role_id1)
print(role_id2)
if role_id1 in member.roles:
await member.remove_roles(role_id1)
await member.add_roles(role_id2)
await ctx.send("Users transferred successfully")'''
!d str.join
str.join(iterable)```
Return a string which is the concatenation of the strings in *iterable*. A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") will be raised if there are any non-string values in *iterable*, including [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. The separator between elements is the string providing this method.
and role_id1 and role_id2 are the same role?
Nop
role_id1 = server.roles[0]
role_id2 = server.roles[0]
I am trying to transfer from one role to another
you're setting them to the same role
` not '
I changed them in the loop
Role_name
Wasn't used I removed it
Sorry I forgot to delete the var
Also don't use __eq__ directly use == instead