#discord-bots

1 messages · Page 215 of 1

radiant bough
#

command?

naive briar
#

What else

#

And did you invite your bot with app commands scope

radiant bough
#

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)
radiant bough
#

@naive briar ^

echo wasp
#

aiohttp unclosed connection when have session.close where it should be

idle surge
#

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))
radiant bough
#

I don’t think self.stop() will remove the drop down but will make it so that no one can interact anymore

idle surge
slate swan
idle surge
slate swan
radiant bough
idle surge
#

where?

#

wouldnt that just delete it after 2 seconds

#

no matter if its interacted or not

idle surge
slate swan
#

do it in the select's callback then

idle surge
#

I tried "await interaction.message.delete()" it just doesnt work.

#

get a 404 error

stable maple
#

Hello
Does anyone know how to reference a .ui file for custom QListWidget list item ?

karmic nimbus
#

how to make on_message(message) read only from certain channels?

steady wedge
#

how do i make chathpt in minecraft as a discord bot

#

FROM SCRATCH

fresh iron
#

so if i have to run my bot on docker container, where can i host it, im new to this.

slate swan
vale wing
# steady wedge FROM SCRATCH

Oh from scratch? Well you will need like a hundred (or several hundred) nvidia A100's to train the neural network to start with

slate swan
#

Fr

steady wedge
#

i might have commited a troller

fresh iron
#

na im looking for a completely free service as my bot doesnt require much

steady wedge
#

but that's an interesting perspective

vale wing
#

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

vale wing
#

Oracle, amazon aws, microsoft azure

radiant bough
#

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

unkempt canyonBOT
#

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.
vocal snow
#

or, subclass View and take the bot instance in the _init_

radiant bough
vale wing
#

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()

slate swan
#

can i use the on_message event for responses ?

vocal snow
slate swan
#

like if a bot sent a message by an interaction response , will the other bot who has on_message work with it ?

vocal snow
valid elbow
#

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?

slate swan
gilded harness
#

sup

flat haven
#

why does python hate me

vocal snow
slate swan
tough cedar
#

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? 👁️

gusty flax
#

Maybe smth with workflows or smth? Idk what they rlly are.

tough cedar
#

well thanks for the ideas anyways

#

🫡

tough cedar
#

lmfao

feral timber
#

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

gusty flax
#

😄

tough cedar
gusty flax
feral timber
#

I literally suck at Docker

gusty flax
feral timber
tough cedar
#

okay, that'd be great

#

thank you :D

gusty flax
#

Wait then who was the dude who was rlly good at docker. I was like 96.3% sure it was you.

feral timber
feral timber
hushed galleon
feral timber
#

ty ty

#

Google results kept re-routing me to Docker's main site asking me to make an account

sick birch
#

Hi @feral timber
What brings you to my abode today?

feral timber
#

The oops is strong in this here young cadet

sick birch
#

For once

unkempt mauve
smoky sinew
#

what do you mean it's not succeeding

unkempt mauve
smoky sinew
#

probably because you are doing followup.send with the paginator

unkempt mauve
smoky sinew
#

only send one of them

unkempt mauve
#

huh

smoky sinew
#

remove the followup.send

#

what is dispie

unkempt mauve
#

that is built for pagination

slate swan
#

make your own paginator so you actually get to know whats happening in the code, the lib's code doesnt look too perfect

smoky sinew
#

it committed pycache to git bruh

slate swan
#

the documentation doesn't follow a fixed style too, and the typing isn't alright either

shut briar
#

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

unkempt mauve
#

its hard to deal with this without followup.send

shrewd apex
#

!pypi reactionmenu

unkempt canyonBOT
#

A library to create a discord.py 2.0+ paginator. Supports pagination with buttons, reactions, and category selection using selects.

unkempt mauve
#

I said the issue is with the defer

shell wing
#
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

slate swan
slate swan
shell wing
slate swan
#

whats the error

#

!d traceback.format_exc takes an argument

#

wait it doesn't

shell wing
slate swan
shell wing
# slate swan 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:
smoky sinew
#

there is a good async websocket library

shut briar
#

Is there an article on that

smoky sinew
shut briar
#

I know nothing about websockets lol

naive umbra
#

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

smoky sinew
shut briar
#

Oh ok but the program I’m sending it to isn’t hosted anywhere

#

It’s not a website

smoky sinew
#

anything can open websockets

#

as long as it has an ip address

shut briar
#

It’s javacript code that gets auto injected to website consoles upon load

#

So that’ll work?

smoky sinew
#

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

shut briar
#

Yea

#

It’s so that me and my friend can communicate in school cause it’s a school chromebook

smoky sinew
#

makes sense

shut briar
#

Welp looks like I have a lot to read up on about websockets

naive umbra
#

web sockets will be a hell to manage for this, please look into message queues/brokers

smoky sinew
#

why so

#

i've built a two-way websocket chat in only 50 lines before

#

it's not anything harder than rabbitmq

naive umbra
#

web sockets and message queues work at different layers

smoky sinew
#

it's the same principle

naive umbra
shut briar
#

When I search up websockets tutorial on YouTube tho all the videos are like 3 hours long

smoky sinew
#

just look at the websocket python docs

#

for javascript look at mdn

shut briar
#

Is it hard for someone to learn who has no knowledge on http connections

#

Besides webhooks

naive umbra
#

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

smoky sinew
#

the receiver is simply a discord bot, it can still manage multiple clients

naive umbra
shut briar
naive umbra
#

and the bot

smoky sinew
#

the discord bot is receiving messages from the browser clients

naive umbra
smoky sinew
#

yeah

naive umbra
#

although doable with web sockets, message queues will remove a ton of headache

shut briar
naive umbra
#

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

shut briar
#

I thought Tampermonkeys supposed to fetch it somehow

smoky sinew
naive umbra
naive umbra
#

this is what a message broker does for you

smoky sinew
#

what is even the benefit here

naive umbra
smoky sinew
#

why would i

naive umbra
naive umbra
smoky sinew
#

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

naive umbra
#

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

slate swan
smoky sinew
#

that can describe every transfer protocol in existence

#

"a software that enables applications to communicate with each other"

#

it's the same idea

naive umbra
#

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]

naive umbra
slate swan
#

a websocket with proper auth would be more than enough for the purpose, using rabbitmq seems a bit excessive

shut briar
#

whats faster / easier / more efficient / easier to learn for a beginner

naive umbra
#

but sure, web sockets works as i said earlier

#

you just get to deal with.. well... web sockets..

slate swan
smoky sinew
#

it's nothing more than a chat with a username and message

regal cove
#

Why do my buttons stop working after around 15 minutes?

slate swan
unkempt canyonBOT
#

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.
regal cove
slate swan
#

you need to pass it to View, not the Button

shut briar
#

is there a better way to communicate between two different computers using tampermonkey, or is using a discord bot the way to go

hushed galleon
regal cove
slate swan
#

remove that *

#

you don't need the *,, it's used only in function signatures

smoky sinew
hushed galleon
#

still means you're opening it to the web

regal cove
#

alright thank you i will go and test it now

hushed galleon
shut briar
#

or can it communicate directly through tampermonkey somehow..

smoky sinew
shut briar
smoky sinew
#
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

smoky sinew
slate swan
#

what's tampermonkey?

smoky sinew
#

a user script thing

shut briar
slate swan
#

wow that sounds useful, but you dont actually need it here

shut briar
smoky sinew
#

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

shut briar
#

i dont have a server idk how that works

smoky sinew
#

the websockets library handles the server part for you

#

you simply have to run it with your computer

shut briar
#

u can open it on a chromebook?

smoky sinew
shut briar
#

i mean .html

smoky sinew
#

yeah

slate swan
#

any browser~

smoky sinew
#

any browser can open html files

shut briar
#

ok alr

#

oh its like a website

#

but not searchable

smoky sinew
#

why not

shut briar
#

sorry if im naive but im tryna learn everyone starts somewhere yk

smoky sinew
#

an html file is a website

#

web servers just happen to serve them

hushed galleon
smoky sinew
#

and also a server can handle multiple clients at once

#

without having to discover them yourself

regal cove
hushed galleon
#

setup_hook like the example shows is fine, and it applies to every button contained within the view you give it

vital glacier
#

    @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

smoky sinew
vital glacier
#

yeah

smoky sinew
#

are you sure you don't have any duplicate rows?

vital glacier
#

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

vital glacier
dull terrace
#

almost at 7000 lines of code for my bot ablobsweats

vital glacier
#

He has a vps providing service lol

dull terrace
#

anyone have ideas for general server features or pvp minigames

vital glacier
#

The vps is running on ubuntu 20.04

sick birch
#

At a certain size for my projects I focus on setting up robust infrastructure, then continue making more features

dull terrace
#

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?

sick birch
#

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

smoky sinew
#

at the same time doing that prematurely can also get you stuck without making any actual features

dull terrace
#

it's hard to imagine even with my crappy coding that will become much of an issue

sick birch
#

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

dull terrace
#

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

sick birch
#

Just food for though, really. You don't have to

dull terrace
#

or cloud whatever

#

i try to think about it but ultimately it seems better to focus on performance as that issue comes up

slate swan
sick birch
#

I personally find that to be the hard part :P

smoky sinew
#

my new bot only has a tag system and it's probably around 700 lines

sick birch
#

You can always add new features or commands to your bot - that isn't really all that difficult nor important

cloud dawn
#

Having a bot with 1000+ lines for just /ping is pretty normal py_guido

dull terrace
#

It is important if you're middling under 1k servers tho

dull terrace
#

Or at least improving features if it's possible

sick birch
#

I would argue good code organization and infrastructure is always important

slate swan
#

How do you define "good"?

#

Robust, efficient, readable?

dense jackal
#

How can I remove a user from a list I created

slate swan
#

Or all of the above aniblobsweat

dull terrace
dense jackal
#

Cause when I do ticketer_list.remove(ctx.author.id) it says like ctx is not defined

#

That got me confused

dull terrace
#

But I guess also don't make a sandwich in a way that's impossible to mass produce later

sick birch
smoky sinew
sick birch
#

Pretty much the same concept

cloud dawn
#

I mean lines go pretty fast.

sick birch
#

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

smoky sinew
#

it's impossible to finish that way

thin raft
smoky sinew
dull terrace
thin raft
#

okok

#

one dude yesterday I think had like over 3+ lines in a same file

smoky sinew
cloud dawn
#

!e print(7000/31)

unkempt canyonBOT
#

@cloud dawn :white_check_mark: Your 3.11 eval job has completed with return code 0.

225.80645161290323
thin raft
#

can you use tree command @dull terrace ?

#

I am intrigued rn

#

do tree /F to show files in win

slate swan
dull terrace
#

Alright prepare to cringe

thin raft
#

my keyboard registers the keys it wants

dense jackal
#

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

cloud dawn
slate swan
cloud dawn
#

Organization🗿

thin raft
#

use folders

#

it looks clean tho

slate swan
dull terrace
#

Idk about clean it's pretty chaotic

slate swan
#

And the error traceback itself preferably.

idle surge
#

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))
slate swan
idle surge
#

It doesnt delete the embed attached to it though

#

just the dropdown

slate swan
#

you said you want to remove dropdown

smoky sinew
idle surge
idle surge
smoky sinew
idle surge
#

In the same place as the view?

smoky sinew
smoky sinew
idle surge
#

Ima try it in like 5 minutes. Just need to do something real quick. Thanks for the help.

smoky sinew
#

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

idle surge
smoky sinew
#

that shouldn't happen...

idle surge
#

if I were to delete the view it deletes just the button but If I did interaction.message.delete it deletes the whole thing.

smoky sinew
#

a view can hold any number of select menus (dropdowns) and buttons

#

and a message can hold multiple embeds and one view

idle surge
#

I was able to fix it though, I did:

        await interaction.response.defer()
        await interaction.delete_original_response()
idle surge
smoky sinew
#

not only the embed and view

slate swan
#

thats all they have in the message tho

#

honestly no point in deleting the message when its ephemeral

ionic garden
dense jackal
#

Why does my bot say interaction failed after like 1min if you haven’t interacted with it

smoky sinew
#

because it times out

dense jackal
#

I mean reaction roles buttons doesn’t time out

smoky sinew
#

what are you referring to

dense jackal
#

Like

#

Those never times out

smoky sinew
#

try this

dense jackal
#

Kk

dense jackal
red kindle
#

can someone please help me figure out the problem

slate swan
#

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)

slate swan
# dense jackal Is there a way to not time it out?

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

smoky sinew
smoky sinew
#

there is no View.start or Button.start method

slate swan
# smoky sinew what

you can sync your buttons like that so it wont timeout aswell, i did it with my ticket system

smoky sinew
#

what library

slate swan
#

i dont use any library for it other than discord's regular library, it works for me like that

smoky sinew
#

what's discord's regular library

slate swan
smoky sinew
#

because that function does not exist

slate swan
#

oh wait no its self.add_view(classname())
then you import the button class

smoky sinew
#

ok

#

you mean view class

red kindle
smoky sinew
#

we can only help with python here

woeful wave
#

Hi

#

Can I get help with python?

slate swan
woeful wave
slate swan
smoky sinew
dense jackal
#

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.

ionic garden
smoky sinew
#

they serve different purposes

ionic garden
#

but like they have virtually the exact same structure

naive briar
#

Take strings as arguments and use it in the class

gusty flax
dense jackal
#

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

gusty flax
#

Id rather help you figure it out, then write it for you.

dense jackal
#

I dont need nothing else to write

#

I just need to solve my error now lol

gusty flax
#

Whats the error.

dense jackal
#

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?

gusty flax
#

Obviously it stems from sending the embed 😅

dense jackal
#

Yep! As said, the moderator’s response embed wont send

#

Unless I open a new ticket

smoky sinew
#

what's the error message though

gusty flax
dense jackal
#

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

gusty flax
#

!traceback

unkempt canyonBOT
#
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.

gusty flax
#
TypeError: can only concatenate str (not "int") to str```This is the error message of that traceback.
dense jackal
#

ouf sorry -- UnboundLocalError: cannot access local variable 'embed_reply' where it is not associated with a value

#

this?

gusty flax
dense jackal
#

Lmao alright

smoky sinew
dense jackal
#

[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

gusty flax
smoky sinew
#

@dense jackal this is your issue

gusty flax
#

Wait, they sent the code?

dense jackal
#

alright yeah ive heard python requires a good indentation in order to work, will try it. ty

dense jackal
#

I dont understand why it works sometimes and other times it doesn't tho

smoky sinew
#

or technically not

gusty flax
smoky sinew
#

i think the else part is just not running

dense jackal
#

where do you want me to intend it tho? it keeps giving me red lines everywhere

smoky sinew
#

but if statements do not create scope

smoky sinew
dense jackal
gusty flax
smoky sinew
#

what does that mean

gusty flax
#

Send ur whole script. I dont see it. @smoky sinew

dense jackal
#

This

smoky sinew
dense jackal
smoky sinew
#

yes there is

gusty flax
smoky sinew
#

look closely

gusty flax
#

Embed_reply is too far forward

smoky sinew
#

notice how these don't align

gusty flax
#

the await is fine where it is.

smoky sinew
#

actually probably yes

#

you're only using 3 spaces on the other lines

dense jackal
#

Want me to send updated script?

gusty flax
#

Push ur embed_reply lines to the right.

dense jackal
#

Like that?

gusty flax
smoky sinew
#

yup

dense jackal
#

Alright, will let you know if there’s anything wrong

#

Ty

echo wasp
#

where do I ask about python database in a discord bot?

naive briar
echo wasp
unkempt mauve
naive briar
#

Just create your own paginator

#

Whatever library you're using looks like it's poorly written

unkempt mauve
echo wasp
slate swan
#

cuz its discord 🗿

#

its actually the most active topical channel iirc

echo wasp
#

so sadly I have to post in the other channel

karmic nimbus
#
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

bright wedge
karmic nimbus
#
@bot.event
async def on_ready():
    print("Ready")
    await load_extensions

??

naive briar
#

Or just functions in general

karmic nimbus
#

not really, I'm new in coding

magic minnow
#

hello! im new to py and looking forward to make a discord bot using it. Anyone there to guide me pls

naive briar
#

You have to call the coroutine function (async function) for it to return a coroutine then await the coroutine

pulsar bridge
#

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?

safe stag
vocal snow
magic minnow
vocal snow
#

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

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

safe stag
unkempt mauve
vale wing
unkempt mauve
#

I am talking about buttons

vale wing
#

Yes it is there as well

#

Formula for max page and checks

unkempt mauve
#

your code is complexed

vale wing
#

It's "complex" because of typehints I presume 😀

#

Other than that it's pretty clean

white citrus
#
  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")```
vale wing
#

!d nextcord.ui.string_select

unkempt canyonBOT
#

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").
vale wing
#

In your case they clearly are strings

white citrus
#
    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

vale wing
#

Oh hell why not use time conversion

white citrus
vale wing
#

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()]```
shrewd fjord
#

Make a simple View pagination ig 🗿

vale wing
#

But I still advise to use time conversion

#

!pypi durations-nlp

white citrus
#

but this is not about my error

unkempt canyonBOT
white citrus
#

can we continue with the error?

vale wing
#

You need to parse actual_options to options in decorator

white citrus
vale wing
#

They are strings

vale wing
white citrus
vale wing
#

Yes and it expects list of SelectOption, not list of str

#

Clearly visible isn't it

white citrus
#

How can i make a followup empfemeral?

unkempt mauve
naive briar
#

Do you know how views work

vale wing
#

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

proper plume
#

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)

vale wing
#

Cogs are merely a way of organising code (and dynamic updates) just telling

naive briar
#

What

vale wing
proper plume
unkempt mauve
vale wing
#

discord.ui.View.callback does not

vale wing
unkempt mauve
proper plume
naive briar
vale wing
naive briar
#

You need to assign a callback to the buttons

vale wing
naive briar
#

!d discord.ui.Button.callback

unkempt canyonBOT
#

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.
unkempt mauve
naive briar
#

And did you assign to the buttons?

#

No

unkempt mauve
#

wdym

#

how do I assign (I am dumb)

vale wing
#

You have callback method in your View subclass, it will never be invoked by internals

proper plume
#

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

vale wing
#

That thing is pretty complex

#

If you really don't know python that would turn into spoonfeeding

proper plume
vale wing
#

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```
unkempt mauve
#

Callback missing one required positional argument 'button'

naive briar
#

Why don't you just declare it with the button deco

#

!d discord.ui.button

unkempt canyonBOT
#

@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.
unkempt mauve
naive briar
#

What's the problem

shrewd fjord
#

;-;

shrewd fjord
#

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

unkempt mauve
shrewd fjord
#

And then edit the buttons according to the pages

shrewd fjord
#

🤷

unkempt mauve
#

if I do @discord.ui.button(label='Previous', disabled=True) it will be always disabled if I am not wrong

shrewd fjord
#

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

unkempt mauve
#

the callback requires discord.ui.Button right

shrewd fjord
unkempt mauve
shrewd fjord
#

self.somename.disabled=False

#

Some name is the callback name

unkempt mauve
#

o

#

if I get back to the first page, I will make a if condition where the button will be disabled right

shrewd fjord
#

if ....==1:
disable it and edit the embed

unkempt mauve
#

same for the next but reverse

shrewd fjord
#

Then also do
if .... == len(a_list_of_embeds):
disable the right button

unkempt mauve
#

hm

shrewd fjord
unkempt mauve
#

thats the thing I needed to know

#

finally someone understood my problem

shrewd fjord
#

Pretty simple 🗿

#

finally i understood some one's problem actually

unkempt mauve
shrewd fjord
#

I am too bad at understanding stuffs lol

unkempt mauve
#

and this "Pagination" started from morning

#

and its night already

shrewd fjord
#

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

glad cradle
#

I have a package for disnake that handles pagination logic

cunning iris
#

what's the best way to store user items for a small bot, json file with a dictionnary in it ? or smth else ?

smoky sinew
#

sqlite

cunning iris
# smoky sinew sqlite

I meant small bot, just to use with a small group of people, no need for a huge db 😄

smoky sinew
#

that's why it's named lite

sick birch
smoky sinew
#

cassandra 💀

gusty flax
alpine cove
unkempt mauve
alpine cove
#

its shit but works xD

shrewd fjord
unkempt mauve
#

Now the issue is the next button is not disabled when the pagination has only one page

shrewd fjord
#

This will return True if the current page is equal to the list and will return false if current page is not equal

unkempt mauve
#
        if len(self.pages) == 1:
            self.next_page.disabled = True
            await self.message.edit(view=self)```
#

I know it takes a few nanoseconds

shrewd fjord
#

The way u r doing is you need to atleast interact the buttons in order to disable it🗿

unkempt mauve
#

it disables itself

#

just takes a few nanoseconds

shrewd fjord
#

Ugh ig u r doing outside the callback then i assume?

unkempt mauve
#
@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
unkempt mauve
#

how do i insert pages there then

shrewd fjord
#

That's a cool ques 🗿

#

Wait lemme try smthing

unkempt mauve
shrewd fjord
#

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

smoky sinew
#

see what i did in my paginator

shrewd fjord
#

All bros suggesting their paginators 😔😔

smoky sinew
shrewd fjord
#

While i dont have mine to suggest

smoky sinew
#

ok i just updated it

ionic garden
#

something's wrong with intellij

terse orchid
#

quick q, anyone know what the latest discord.py version is?

#

found it, its 2.2.2

thin raft
unkempt canyonBOT
#

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.

thin raft
#

2.2.2

dull terrace
#

can someone explain how to properly version something to me doge_kek

#

why 2.2.2 not 2.22 or 2.3

dull terrace
slate swan
#

how to make an image slash option

#

yo?

smoky sinew
dull terrace
#

i think they mean upload a file

smoky sinew
#

instead of 0.1.0

dull terrace
#

then you can do

if file.content_type == "image/png":```
#

to check if it's a type

slate swan
smoky sinew
#

ah

slate swan
#

nvm

smoky sinew
#

just typehint it as attachment

slate swan
#

i got it

#

ty yall

dull terrace
#

iirc you can't edit ephemeral messages?

stone gate
#

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?-

stone gate
#

yes

stone gate
#

thanks, ill take a look at it

smoky sinew
#

just add that decorator to your function

#

and your function takes in an interaction object instead of context

stone gate
#

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)`
dull terrace
#

name can't have spaces

stone gate
#

like that?

dull terrace
#

or capital letters i think

smoky sinew
#

@discord.app.commands.get_sheet

#

replace this with @discord.app_commands.command

#

and you still need to remove all the places you use ctx

silk fulcrum
smoky sinew
#

if you're not using any cogs then just do @client.tree.command()

dull terrace
#

for the record ctx or interaction are fine

smoky sinew
dull terrace
#

as long as you use it throughout

stone gate
#

so the await cxt.send(embed=response) should be noe something like interaction.send(embed=response)

smoky sinew
#

no

#

!d discord.InteractionResponse.send_message

unkempt canyonBOT
#

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.
smoky sinew
#

interactions have responses that they have to send

#

you must send one and you can only send one

silk fulcrum
#

I don't have problems with hybrid commands

stone gate
#

so, something like send_message(embed=response)

silk fulcrum
#

maybe it's that I got used to them

smoky sinew
smoky sinew
stone gate
#

thanks! i think im understanding now

smoky sinew
stone gate
#

should i change something on my bot.py file or does this work directly?

smoky sinew
#

yes you need a prefix command to sync your slash commands

silk fulcrum
smoky sinew
#
@client.command()
async def sync(ctx):
    await client.tree.sync()

@stone gate something like this

stone gate
#

aight

smoky sinew
#

and run it every time you add/delete commands, or update command info

stone gate
#

either the bot does not sync or the command isnt working '. .)

#

oh i get this

NameError: name 'client' is not defined```
dull terrace
#

did you use bot or client

stone gate
#

wdym?;;;

dull terrace
#

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

stone gate
#

ohh i see

#

lemme check

dull terrace
#

and this is above?

stone gate
#

not above everything

iron turret
#

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

dull terrace
#

i don't understand how it can be undefined unless it's in another file

stone gate
#

oh wait yeah that might be it

#

do i need to define it in every file or just the bot.py file?

dull terrace
#

in that case move it to the same file or from that file, at the top import client from <file_name>

smoky sinew
#

@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

dull terrace
#

although that's probably going to make a circular import

smoky sinew
#

oh my bad

#

wrong person

stone gate
iron turret
#

Okay, whats a right time?

#

like 1 min, 2min?

smoky sinew
#

i think 20-30 seconds could work

#

better to be on the safe side though

iron turret
#

👍

#

thanks!

dull terrace
smoky sinew
#

because a string was passed

dull terrace
#

oh i see

iron turret
#

Yay it worked!

#

Thx 😄

smoky sinew
#

@stone gate

#

what is your full code

stone gate
#

like this¿

smoky sinew
#

you're supposed to press the save button and send the link, don't send a screenshot

slate swan
#

ctrl + s

#

and send link

stone gate
slate swan
#

it should change upon saving

stone gate
#

sorry myb

smoky sinew
#

send the other files too

stone gate
#

aight

slate swan
#

since you are loading extensions no need to add commands too

smoky sinew
#

it's because you are using client in the commands file

slate swan
#

i guess

vale wing
#

Why'd you add 2 commands separately? I mean technically it is okay but what is the point

stone gate
smoky sinew
#

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

stone gate
#

wait i dont fully understand

smoky sinew
stone gate
#

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?

smoky sinew
#

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

stone gate
#

so this is what my directory looks like

#

inside of commands i obviusly have calculate.py and get_sheet.py

stone gate
#

i dont know the specific terms for those actions, but im able to read it that way

smoky sinew
stone gate
#

oh ill have more commands soon

#

i just want to first understand how to do slash commands first before moving on

dull terrace
#

what you've got already works if you move it into the same file where you define client

stone gate
#

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!

slate swan
#

how can I add option_enums to discord_slash api for discord bot

smoky sinew
#

i don't think there's such thing as option enums, it's just an autocomplete

slate swan
#

also they aint that outdated

smoky sinew
#

you know discord.py has its own slash command system

smoky sinew
#

discord_slash was literally created late 2021

stone gate
#

how do i set up a cog?

smoky sinew
stone gate
#

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

smoky sinew
stone gate
#

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

smoky sinew
#

you don't even need cogs though

stone gate
#

so should i just write everything on the main file? wouldnt that get messy really fast?

smoky sinew
#

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

stone gate
#

i see

smoky sinew
slate swan
slate swan
smoky sinew
#

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)

stone gate
#

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"

smoky sinew
#

what is your bot like?

stone gate
#

like, what does it do?

smoky sinew
#

yeah

stone gate
#

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

smoky sinew
#

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

stone gate
#

hmmmm, let me see, like around 20?

smoky sinew
#

it shouldn't be a problem to put them in one extension or the main file if they're all for the same purpose

stone gate
#

i see

smoky sinew
#

do you need me to explain how cogs / extensions work?

smoky sinew
#

looks pretty good, though i wouldn't make a separate extension for each command

#

then you will have 20+ files

stone gate
smoky sinew
#

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

stone gate
smoky sinew
#

wdym the documented stuff was wrong?

stone gate
#

commented* those were lines/stuff he fixed

smoky sinew
#

ah i see

full lily
#

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?

smoky sinew
#

!d discord.ext.commands.Greedy

unkempt canyonBOT
#

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`...
full lily
#

ah that would be it. Vaguely remembered something about that

stone gate
#

okay so now, what should i add on my main file?

full lily
#

What if I wanted something custom for this? for example strings that begin with letter "a"

smoky sinew
#

i don't think you can do that with the default one

full lily
#

okidoke, sounds good

smoky sinew
#

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

stone gate
smoky sinew
#

the second one

stone gate
#
    await client.load_extension("commands.calculate")
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: 'await' outside function```
smoky sinew
#

try this

#
@client.event
async def setup_hook():
    await client.load_extension("commands.calculate")
stone gate
#

heres my main, it reads the token but i get another message

smoky sinew
#

what is it

stone gate
#
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

unkempt canyonBOT
#

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!

stone gate
#

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```
smoky sinew
#

what does your code look like?

#

did you await Bot.add_cog?

#

also did you reset your token

stone gate
smoky sinew
#

can you paste your code again

#

!paste

unkempt canyonBOT
#
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.

stone gate
upbeat ice
#
    bot.add_cog(CalculationCog(bot)) ```
slate swan
smoky sinew
#

oh that's my fault

slate swan
#

and you need to await the add_cog

smoky sinew
#

i forgot to put that

stone gate
#

async def setup(bot):
await client.add_cog(CalculationCog(bot))

#

like that?

slate swan
#

bot.add_cog

smoky sinew
#

capitalize Cog

stone gate
#

yeeeahhh it works

smoky sinew
#

@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]):
    ...
full lily
#

thanks for taking the time to conjure this

#

very nice

smoky sinew
#

np

stone gate
#

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```
smoky sinew
#

replace everything named sheet with self.sheet

stone gate
#

thanks

#

now, with that out of the way, how did the slash commands were made again? Lmao

slate swan
#

this guide explains it well ^

stone gate
#

okay so it kinda worked

#

nevermind it worked

stone gate
#

@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?

smoky sinew
stone gate
#

aight

#

thanks, you helped a lot

dense jackal
#

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

smoky sinew
#

huh

dense jackal
#

The thing we thought we fixed

#

With my intends

#

Well it didnt work

#

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.

upbeat ice
#

would have to see your code

#

otherwise we are just guessing

patent lark
#

yup

dense jackal
dense jackal
slate swan
#

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??

slate swan
#

!intents

unkempt canyonBOT
#
Using intents in discord.py

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.

slate swan
#

I have it

#

show code

#

Wait

shrewd fjord
#

!d discord.Client.wait_for

unkempt canyonBOT
#

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**...
shrewd fjord
#

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

naive briar
#

I'll never understand why people use while loops with wait_for

shrewd fjord
#

Idk 🗿

#

on_message will work too tho

hexed dagger
#

Hi

#

Is anyone available to help?

vocal snow
naive briar
#

Don't ask to ask

smoky sinew
vocal snow
smoky sinew
#

💀

hexed dagger
#

So this is my code to transfer users that have a specific role to another role

#

It's not working

keen talon
unkempt canyonBOT
#
Formatting code on discord

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.

For long code samples, you can use our pastebin.

smoky sinew
#

why are you even calling __eq__ manually

smoky sinew
# hexed dagger

your error is that arg1 is a string and you're passing a string to join

hexed dagger
#

'''@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")'''

keen talon
#

!d str.join

unkempt canyonBOT
#

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.
vocal snow
#

and role_id1 and role_id2 are the same role?

hexed dagger
#

Nop

vocal snow
#
role_id1 = server.roles[0]
role_id2 = server.roles[0]
hexed dagger
#

I am trying to transfer from one role to another

vocal snow
#

you're setting them to the same role

hexed dagger
hexed dagger
#

Wasn't used I removed it

#

Sorry I forgot to delete the var

keen talon