#discord-bots

1 messages Ā· Page 93 of 1

robust fulcrum
#

Like it should need double exp from last one

rugged shadow
#

Bruh 🤦

#

make another property in your player table

#

name it like "required_exp_for_next_level"

robust fulcrum
#

Ok

rugged shadow
#

and "exp_since_last_level_update"

robust fulcrum
#

Can I have one suggestion from you?

rugged shadow
#

what

robust fulcrum
#

Should I reset user exp when they level up?

rugged shadow
#

no

robust fulcrum
#

Ok

#

Anyway i should do 200 exp instead of 100

rugged shadow
#

idk

robust fulcrum
#

Thanks for help tho

robust fulcrum
rugged shadow
#

how old are you?

robust fulcrum
#

hmmm 13

rugged shadow
#

do you have like a spare PC or raspi

brazen raft
#

And can provide an internet connection and power constantly

austere bane
#

i'm trying to get a bot to send spotify url on command, but i can't get it to work. i tried to follow a youtube tutorial.

async def track(ctx, user: discord.Member = None):
    user = user or ctx.author
    for activity in user.activities:
        if isinstance(activity, discord.Spotify):
            await ctx.send(f"https://open.spotify.com/track/{activity.track_id}")```

it says ```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'User' object has no attribute 'activities'```
#

sorry, i'm really new to this... anyone know what i'm doing wrong?

brazen raft
#

Apparently ctx.author is of type discord.User. discord.User objects don't have activity and activities attributes

#

Try using user: discord.Member = commands.Author instead of doing the user = user or ctx.author thing

austere bane
#

thanks for the tip, @brazen raft but now it said : AttributeError: module 'discord.ext.commands' has no attribute 'Author'

brazen raft
#

Are you using discord.py?

austere bane
#

yes

brazen raft
#

Latest version?

#

Which I think is 2.1 now

#

You can update with

py -m pip install -U discord.py

if you are on Windows

austere bane
#

i use ubuntu

#

is there something i should import, which i might not have? :S

wicked atlas
austere bane
#

Thanks, @wicked atlas i didn't have that, but i still get the same message

#

Also, I'm on the latest version it seems

wicked atlas
#

You’ve enabled them both in the dev portal and in the code?

digital charm
#

I'm pretty sure there's smth wrong with the code please let me know what is wrong
The code - https://pastebin.com/Z9CNGzG3
I would be really grateful if u answered by replying to this is message
Thanking you in anticipation...

wicked atlas
digital charm
#

basically the end part of the code is crucial

austere bane
#

looks like i hadn't in the portal @wicked atlas do you know if i need to generate a new token, because i still get the same errors... :\ AttributeError: 'User' object has no attribute 'activities'

wicked atlas
#

This is odd then

#

Are you running this command in a server, or a DM?

mental hollow
austere bane
#

I tried DM, but it seems to be working in server now.

#

šŸ˜„

#

is there a reason it doesn't work in DM?

wicked atlas
#

You won’t be able to get Member objects in a DM, it will only give User objects, since a Member object represents a member of a server

austere bane
#

Aha

#

Thank you very much šŸ™‚

digital charm
#

I'm pretty sure it has to do with

#

discord

mental hollow
#

you didn’t provide any error tc_shrug

digital charm
digital charm
# mental hollow ^

I just said what's wrong... just review the code, no need to run the code

cloud dawn
#
async def planets(user, button: discord.ui.Button):
  button.labal = await Planet
  db = await aiosqlite.connect('player_data.db')
  async with db.cursor() as cursor:
    await cursor.execute("INSERT INTO planet VALUES(?, ?)", (user.id, button.label,))
    await db.commit()
    return
``` this code isn't even used in the class????
#

Also button.labal = await Planet???

slate swan
#

What's more efficient? Photos in files or download via link?
and will the bot go faster on hosting than on localhost?

oblique loom
#

Wait what is the import for discord commands again?

#

I forgot

slate swan
cloud dawn
oblique loom
#

Ohhh I did it backwards, I’m dumb

#

Thanks

slate swan
slate swan
cloud dawn
slate swan
#

i.e. use links to photos instead of downloading from a file?

#

example image

cloud dawn
slate swan
#

It is difficult, if it is a more efficient method, I will use it

cloud dawn
#

Well it's unethical, why would you use resources for something as small as a faster loading time for images if people are used to Discord slow and annoying lazy loading anyways lol

slate swan
#

but sometimes it is so that the interaction will not take place at all because the waiting time was too long. Unless, if I give it to hosting, it will change

robust fulcrum
#

Guys how we can host a discord bot free on Oracle?

cloud dawn
#

iirc you need to be a student

robust fulcrum
#

Btw how we can add arguments to slash command?

bright wedge
#

how i can create a custom function in discord.py?

class Game(commands.Cog):

    def __init__(self, bot):
        self.bot = bot
        bot.add_view(JoinGame())    

    async def create_dolofonoi_chat():
        # do something


    @commands.command(alias=["Start", "START"])
    async def start(self,ctx):
        embed = discord.Embed(title="Start Game.")
        await ctx.channel.send(embed=embed)
        create_dolofonoi_chat()

bright wedge
#

thanks anyway

shrewd apex
#

šŸ‘

bright wedge
# shrewd apex šŸ‘
# its cog file
class Game(commands.Cog):

    def __init__(self, bot):
        self.bot = bot
        bot.add_view(JoinGame())    

    async def create_dolofonoi_chat(self):
          # how i can define the guild because im getting error when i try this:
          guild = self.bot.get_guild(884589903210479637)

      
modern fiber
#

Any free bot hosting? I used heroku but yeah..

sage otter
cloud dawn
slate swan
modern fiber
primal token
#

There's always a catch with free hosting sites as you cant use a companies resources for free, legally, without given them some sort of exchange, most of the time it's money

dull terrace
#

i wonder if you could create a hosting solution based on ads

sage otter
# modern fiber what do you mean by "catch"?

Think for a second. Why would someone host your stuff on their expensive hardware for free without there being some sort of catch. Deta for example collects lots of data and reserves the right to use your software for reasons "within their company"

slate swan
dull terrace
#

the ultimate free hosting solution: use your pc?

sage otter
#

Especially if there’s hundreds and hundreds of people trying to participate in "free hosting" they will have to continue to scale their hardware to keep up. And it’s not cheap.

dull terrace
#

a raspberry pi is actually a pretty neat way i've seen people do it

sage otter
#

I don’t think so.

#

Running your computer 24/7 365 days a year isn’t good for its health.

dull terrace
sage otter
#

With no rest whatsoever?

dull terrace
#

What's bad for your pc is often rapid temperature changes

#

Yeah no reset

cloud dawn
#

Physically as well.

dull terrace
#

In theory, in some ways it's better for your pc than turning it off an on

cloud dawn
#

You can dip your whole pc in water and let it dry for a week and it will be all fine.

dull terrace
#

Raising components to 60c or whatever temp and then letting them cool to room temperature is constantly expanding and contracting material

sick birch
sage otter
#

idk then.

cloud dawn
#

servers are just pc's with extra steps.

sage otter
#

I believed there was difference because one is dedicated for that job with consistent maintenance

sick birch
#

Both are computers

#

Bottom line

#

You can run both 24/7 and work just fine (given you maintain it)

#

heck your phone is a computer

cloud dawn
#

It's just different names because people in that industry like to have fancy words.

sick birch
#

Yeah, and both do exactly the same thing

#

I could prob buy a server and use it as my home computer and play games on it or whatever

#

Similarly companies can buy a dell optiplex and use it as a server

lament mesa
#

Servers are just buff pc's

#

most of the time

sage otter
#

most servers don’t come with gpus

#

from what I’ve seen atleast.

sick birch
#

It’s good processing power

sage otter
#

what kinda servers you be gettin?

sick birch
cloud dawn
#

The majority most likely only has an igpu

sage otter
#

Intel graphics

sick birch
#

Good enough for me :))

dull terrace
#

If you wanna run your own server just buy a raspberry pi though, uses no energy and keep it on 24/7 and forget about it

sage otter
#

Ryzen graphics

cloud dawn
sage otter
#

well yeah.

dull terrace
#

More than enough for bots

sage otter
#

I’m just saying Intel graphics because that’s an example of integrated graphics

sick birch
dull terrace
#

How much power does one actually use, how long could you run it on a lithium battery

sick birch
#

You’d have to check the specs for the power supply

cloud dawn
#

Just slap in a EPYC 7742 and ur good

dull terrace
#

5 watts at full for 4

sage otter
cloud dawn
dull terrace
#

Model zero can run on a 21700(about twice the size of a AA battery) for 28 hours

slate swan
#

Does someone know how I can ask the bot in which channel a specific user is and he replies with the channel. As example I do:
!channel {username}
and the bot replies with the channel where the user is in so I can click on the channelname and I can join etc, example:
The user is currently in the voicechannel {voicechannel}

unkempt canyonBOT
glad cradle
#

this returns a voice state object

#

!d discord.VoiceState.channel

unkempt canyonBOT
#

The voice channel that the user is currently connected to. None if the user is not currently in a voice channel.

slate swan
#

thanks mate, I will read through it

restive tide
#

Anyone able to help in help-broccoli regarding discord bots??

#

i hav to go soon so it will be very helpful

feral frost
#

guys

#

how do i make it so when i click a button the bot its message will be gone ? it works in dm but not in server

feral frost
#

the bot its message

slate swan
feral frost
#

just the message the bot sends

#

the output of what i input

slate swan
#

the bot sends many of 'em
and you input numerous things

#

do you wanna delete the message the button is contained in?

feral frost
#

yes

#

but look at this code you might understand it better

slate swan
#

Is it possible to send a discord bot message without having it to react to a message

feral frost
slate swan
slate swan
feral frost
#

ok

slate swan
feral frost
#

NameError: name 'self' is not defined

slate swan
feral frost
#

?

slate swan
#

just modify it according to your code smh

#

where are you creating the button?

feral frost
#

well idk how thats why i asked

slate swan
feral frost
#

what do you mean with where ?

unkempt canyonBOT
#

@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
slate swan
feral frost
#

inside of the command

#

view things are on the bottem

#

buttons on the top

slate swan
#

you should create a subclass tbh, 'cause I don't see how you'll make no subclassing work in this case

feral frost
#

? i dont even know what a subclass is

feral frost
#

instead of dms

slate swan
#

and could be inaccurate

feral frost
#

ok what is it ?

slate swan
#

and may end up deleting a wrong message in very rare cases

#

you could fetch the history of the channel (last 5 messages) with a check that checks if the message was sent by the bot and the content of the message matches...then you could delete it

feral frost
#

thats the code i send

feral frost
#

you know what nvm do you know how i disable buttons ?

slate swan
slate swan
feral frost
#

ok

#

i do think thats kinda offensive but ok thanks

slate swan
#

lmao

feral frost
#

and you know how i put a cooldown on a button ?

slate swan
#

you'll have to implement that by yourself

feral frost
#

why ?

slate swan
#

...

feral frost
slate swan
# feral frost ?

it isn't implemented by dpy itself, so you'll have to write your own logic for that

feral frost
slate swan
#

code?

feral frost
#

like where do i put it ?

feral frost
slate swan
#

wherevee you wanna disable them from?

feral frost
#

from the other button

#
            em = discord.Embed(description=f"āœ… Successfully sold!", color=color)
            await interaction.response.edit_message(embed=em)
            await update_bank(ctx.author, mul)
            for child in view.children:
                child.disabled = True````like this ???
slate swan
feral frost
#

what message ?

feral frost
slate swan
#

Can someone help me to make a command with discord.Member.voice and discord.VoiceState.channel? I dont know how to use them to get a good output: Im new in discord.py and cant find videos/tutorials how to use it

sick birch
slate swan
#

I just need a simple command where I can search the channel where a specific user is in. Because on the server there are temp voice channels so its hard to find a user in a channel. So I want a command where I can write:
!location {username}
and then the bot replies with the specific channel so I can click on the channel name to get to the channel. And if the user is in no channel it just responds with:
the user isnt in a channel.

But I dont know how to implement it bcs im new in discord.py

sick birch
#

Nvm, you just sent it

slate swan
#

Forgot to send it before, sorry haha

ocean lantern
#

How do you send messages without user sending one first?

slate swan
unkempt canyonBOT
sick birch
#

It’s that easy

slate swan
#

Im kinda lost but I cant find a tutorial or smt to it

sick birch
#

You just call the .voice property on a member object

slate swan
#

Thats the thing, how do I do it. Could you explain that to me

#

I new to make a new bot.command, then async def location as example and then call discord.Member.voice but how do I do it that I can ping the member and it replies with the channel name then

honest shoal
slate swan
honest shoal
#

and it's simple, you get to know about voice state using that

slate swan
mental hollow
#

How can I convert things such as 5m or 2d into a datetime object so then I can use it for member.edit(timed_out_until = …)?

honest shoal
mental hollow
#

could i get an example please?

slate swan
honest shoal
mental hollow
#

oh god

#

yeah I’ll probably stick with the human friendly module

upbeat marsh
#

So how could I host a discord bot on my raspberry pi and be able to easily modify it with SSH?

#

Tired of replit constantly getting banned

faint sapphire
#

when a bot sends a message too big, does it become a file?

dull terrace
faint sapphire
#

true

#

thanks

dull terrace
upbeat marsh
tidal hawk
#

install python3, setup the folder, create a bot & create systemctl instance

#

Make sure you install the correct python3 version

upbeat marsh
#

What's systemctl?

tidal hawk
#

You're going to use it for running the bot on background

upbeat marsh
#

Would it run alongside omv?

tidal hawk
#

omv?

upbeat marsh
#

openmediavault

#

or should i just use my pi 3

tidal hawk
#

idk

#

I just used rpi

upbeat marsh
#

I think the Pi 3 may be better. I'd have better access to it anyways

#

Also, what would be the chance that I get IP banned?

tidal hawk
#

Not sure, why do you think you'd get banned?

upbeat marsh
tidal hawk
#

You'll get rate limited first

#

You sure they are going to request your bot 50 times per second? xd

upbeat marsh
#

That's the treshhold?

tidal hawk
upbeat marsh
#

So should I make the cooldown so you can only use a command once per second?

tidal hawk
#

Perhaps, your choice. But I think there's no need for a cooldown (but that can change when your bot is going to be used in a lot of servers)

upbeat marsh
#

Either way, if some moron starts spamming stuff, I'd take the bot offline

tidal hawk
#

okay xd

upbeat marsh
#

I read somewhere that you can use git to edit the discord bot with ssh

tidal hawk
#

I use Vscode with remote ssh extension

upbeat marsh
#

Would 1GB be enough for the bot or should I run it on my Pi 4 (4GB) that's running a NAS server

tidal hawk
#

1 gb of ram or storage?

upbeat marsh
#

RAM

tidal hawk
#

Atleast 2 GB's is recommended

upbeat marsh
#

So 1GB wouldn't work?

tidal hawk
#

You can try it

upbeat marsh
#

Well wait

#

replit has 1GB of RAM allocated

#

And the bot runs fine

tidal hawk
#

Welp then your good

weary flume
#

where should i go to learn about mongodb

tidal hawk
#

Codeacademy?

weary flume
#

ok

slate swan
#

how to defined time?

tidal hawk
#

integer

slate swan
#
    @commands.slash_command()
    async def timeout(self, ctx, member: disnake.Member):
        await member.edit(timeout = "60")```
tidal hawk
#

number without " "

shut axle
slate swan
#

I already fixed it but thanks anyways

silk fulcrum
#

because discord.py takes datetime / timedelta for a timeout

#

not an int

#

and also it's until and it's an arg, not a kwarg iirc

#

oh wait you are using edit

#

i dont think edit has timeout at all

winged coral
#

This is disnake

#

Perhaps different?

#

Yeah it takes the kwarg and also a float

#

But not a string

strange carbon
#

can someone help me create something with python dm me if your willing to it inculdes a link so i can’t send it here

tidal hawk
primal token
#

And dont hit me with the:

import discord as disnake
```![pithink](https://cdn.discordapp.com/emojis/652247559909277706.webp?size=128 "pithink")
cobalt crane
#

yo, anyone here know how to save a file a user sends? Like if I attach a file with this message, I want the bot to save that file as a varaible. Thx

slate swan
dire folio
slate swan
#

how would i do that?

dire folio
#

Sorry, I haven't done this in a while so I don't remember much

slate swan
#

ok

#

Someone pls help me in this

slate swan
unkempt canyonBOT
#
NEGATORY.

No documentation found for the requested symbol.

deft hill
#

How do I get a users id from an on_member_join event?

member is just their username and descrimator. Ive tried member.id (how I remember it being from awhile ago, no luck)

#

I forgot to format the string....

rare echo
cobalt crane
#

How would I save a file a user sends in discord. If I enter a file rn I want the bot to save that attachment as a variable.

torn sail
#

!d discord.on_thread_remove

unkempt canyonBOT
#

discord.on_thread_remove(thread)```
Called whenever a thread is removed. This is different from a thread being deleted.

Note that you can get the guild from [`Thread.guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Thread.guild "discord.Thread.guild").

This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.

Warning

Due to technical limitations, this event might not be called as soon as one expects. Since the library tracks thread membership locally, the API only sends updated thread membership status upon being synced by joining a thread.

New in version 2.0.
torn sail
#

what is the different between thread removal and thread deletion?

indigo pilot
#
C:\Users\kaelm\AppData\Local\Programs\Python\Python310\python.exe C:\Users\kaelm\PycharmProjects\mainbot\bot.py 
Traceback (most recent call last):
  File "C:\Users\kaelm\PycharmProjects\mainbot\bot.py", line 2, in <module>
    import discord
  File "C:\Users\kaelm\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\__init__.py", line 23, in <module>
    from .client import *
  File "C:\Users\kaelm\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 47, in <module>
    import aiohttp
  File "C:\Users\kaelm\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\__init__.py", line 6, in <module>
    from .client import (
  File "C:\Users\kaelm\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\client.py", line 36, in <module>
    from . import hdrs, http, payload
  File "C:\Users\kaelm\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\http.py", line 7, in <module>
    from .http_parser import (
  File "C:\Users\kaelm\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\http_parser.py", line 29, in <module>
    from .helpers import NO_EXTENSIONS, BaseTimerContext
  File "C:\Users\kaelm\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\helpers.py", line 732, in <module>
    def ceil_timeout(delay: Optional[float]) -> async_timeout.Timeout:
AttributeError: module 'async_timeout' has no attribute 'Timeout'. Did you mean: 'timeout'?

Process finished with exit code 1```
#

Anyone know what this error means? happens when i start my bot

#

got no clue where to even start to debug

torn sail
#

do you happen to have a file called async_timeout?

indigo pilot
weary flume
#

how can i make my bot delete messages over 4 lines?

rare echo
weary flume
#

4 seperate lines

#

a
A
a
A

#

if it gets to 5 the bot deletes it

rare echo
#

oh i read that wrong

weary flume
#

it was probably me lmao

rare echo
#

i dont know if thats detectable personally only because my thought is the fact that on mobile it could be 10 lines while on a small monitor it could be 3 and a big monitor 1

#

( in the same message that is )

weary flume
#

well

#

i mean not really

rare echo
#

but you could do something like

 if len(message chars) > 20
weary flume
#

ok

#

lemme try that

cobalt crane
#

Anyone know how I can save a attachment as a variable? Like if a user sends an attachment, I want to save that attachment image as a variable to use later. Idk why but I really cannot figure this one out :/

slate swan
cobalt crane
#

I don't think that'll work because I'm going to use the image with pytesseract next. I want the image to be able to be used like that later

slate swan
#

then you would have to save the image locally

cobalt crane
#

yeah pretty much, idk how to do it tho

slate swan
#

what bot lib are you using

cobalt crane
#

wdym

slate swan
#

the library for the discord bot?

#

dpy, nextcord, pycord, etc...

cobalt crane
empty aspen
#

hoi!

slate swan
#

How would I make it so a bot selects a random amount of people from a server, and gives them a role

unkempt canyonBOT
#

random.choices(population, weights=None, *, cum_weights=None, k=1)```
Return a *k* sized list of elements chosen from the *population* with replacement. If the *population* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").

If a *weights* sequence is specified, selections are made according to the relative weights. Alternatively, if a *cum\_weights* sequence is given, the selections are made according to the cumulative weights (perhaps computed using [`itertools.accumulate()`](https://docs.python.org/3/library/itertools.html#itertools.accumulate "itertools.accumulate")). For example, the relative weights `[10, 5, 30, 5]` are equivalent to the cumulative weights `[10, 15, 45, 50]`. Internally, the relative weights are converted to cumulative weights before making selections, so supplying the cumulative weights saves work.
sick birch
#

!d discord.Guild.members

unkempt canyonBOT
sick birch
#

!d discord.Member.add_roles

unkempt canyonBOT
#

await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.

You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
sick birch
#

those are the 3 things you need

slate swan
#

I dont get what it means by the eights and cum_weights

sick birch
sick birch
slate swan
#

if i did random.choices(hello, k=2)

#

it would pick 2 of those

sick birch
slate swan
# sick birch right

what would i do after then? like it picked random choices, but how would i call them

sick birch
#

You can do whatever you want with that

#

In your case, loop over all of them and add_roles

slate swan
sick birch
#

No, it returns a completely new list

slate swan
sick birch
slate swan
sick birch
#
my_list = [1, 3, 5]
new_list = random.choices(my_list, k=2)

here it would be new_list

slate swan
#

OHH

#

my bad

sick birch
#

sorry i explained that pretty badly

slate swan
sick birch
#

Also why would you need get_member

slate swan
#

This one, it explained nothing?

sick birch
#

I think it explains more than enough

#

property members of a discord.Guild instance, which returns a sequence of discord.Member instances

#

a list of members that belong to this guild
All you need to know, really

slate swan
sick birch
#

That's what I'm getting at, yes

slate swan
#

thats why he is trying to explain to u lol. if you dont understand that then you should learn basic py

sick birch
#

I understand the question, no worries there. I'm just trying to get them to arrive on the solution on their own instead of just me giving the solution away

slate swan
#

no i mean that statement was meant for him lol

sick birch
#

Ah, sorry

slate swan
#

I learnt everything from yt vids

#

and i dont know what that means

sick birch
#

So random.choices(...) first argument is a list which it'll take k random items out of

#

You want to pass in discord.Guild.members to it

sick birch
#

It spits out k random discord.Member instances

#

On which you'll iterate and apply add_roles() to

#

It's a 3 part solution

slate swan
sick birch
#

You call it on an instance, not the class

#

For instance (see what I did there? i'm funny), you may call it on ctx.guild

slate swan
#

ctx.guild.members

sick birch
#
@bot.command()
async def my_command(ctx: commands.Context, ...) -> None:
  random_members: list[discord.Member] = random.choices(ctx.guild.members, k=5)
  for member in random_members:
    await member.add_roles(...)

here's a good starting point

cobalt crane
cobalt crane
#

def check(m):
return m.content and m.channel == message.channel
msg = await client.wait_for('message', check=check)

async def main():
  discord.Attachment.save('test', *, seek_begin=True, use_cached=False)
sick birch
#

Yeah discord.Attachment needs to be an instance, not the class

#

!d discord.Message.attachments this returns a list[discord.Attachment]

unkempt canyonBOT
slate swan
#
@bot.command()
@has_permissions(administrator=True)
async def addrole(ctx, role=None, amount=None):
  random_members: list[discord.Member] = random.choices(ctx.guild.members, k=amount)
  for member in random_members:
    await member.add_roles(role)
  await ctx.send(f'Completed adding {role} role to {amount} members')``` was my code
cobalt crane
# unkempt canyon

I have intents.message_context already enabled though. If I can get the message.content fine but I cant get the attachments

sick birch
#

it might be "5" for example

slate swan
#

so if the message has an attachment it would be

sick birch
#

You can use discord.py's handy typing feature:

@bot.command()
async def my_command(..., integer_argument: int) -> None:
  print(type(integer_argument)) # class <'int'>
slate swan
#

message.attachments[0] would get you the first attachment or only attachment

slate swan
# sick birch `amount` is a string

I think i fixed it now, but it says discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'id'

sick birch
#

What's the full traceback?

cobalt crane
slate swan
#

26.09 03:13:00 [Bot] Traceback (most recent call last):
26.09 03:13:00 [Bot] File "/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 190, in wrapped
26.09 03:13:00 [Bot] ret = await coro(*args, **kwargs)
26.09 03:13:00 [Bot] File "/./Bot2/main.py", line 170, in addrole
26.09 03:13:00 [Bot] await member.add_roles(role)
26.09 03:13:00 [Bot] File "/.local/lib/python3.9/site-packages/discord/member.py", line 1014, in add_roles
26.09 03:13:00 [Bot] await req(guild_id, user_id, role.id, reason=reason)
26.09 03:13:00 [Bot] AttributeError: 'str' object has no attribute 'id'
26.09 03:13:00 [Bot] The above exception was the direct cause of the following exception:
26.09 03:13:00 [Bot] Traceback (most recent call last):
26.09 03:13:00 [Bot] File "/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 1347, in invoke
26.09 03:13:00 [Bot] await ctx.command.invoke(ctx)
26.09 03:13:00 [Bot] File "/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 986, in invoke
26.09 03:13:00 [Bot] await injected(*ctx.args, **ctx.kwargs) # type: ignore
26.09 03:13:00 [Bot] File "/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 199, in wrapped
26.09 03:13:00 [Bot] raise CommandInvokeError(exc) from exc
26.09 03:13:00 [Bot] discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'id'

sick birch
sick birch
slate swan
#

ok

slate swan
#

so then i can do "-addrole @role (number)" and it'll work?

#

you an keep how you have it

#

oh shit

#

ur using ctx cmds lol

sick birch
slate swan
slate swan
#

im not familiar wiht chat cmds but i assume if you mention the role and have role: discord.Role in the function it should work right?

slate swan
sick birch
#

Depending on how large k is

slate swan
#

yeah it just depends on the amount of members you are adding roles too

slate swan
sick birch
#

You need to abide by the ratelimits

slate swan
#

^

#

So I'd have to make it give a role every 1.7 seconds

#

To not get rate limited?

sick birch
#

I'd probably add an asyncio.sleep() to not get ratelimited

#

Sure, set it 2 seconds to be safe

slate swan
#

well with adding roles it just queues up the rest

#

if you are ratelimited. so it will add them it just may take time depending on how many members your adding roles to

sick birch
#

better not to get ratelimited in the first place

slate swan
#

the lib handles it tho you dont actually get ratelimited

#

i believe

sick birch
#

I've seen plenty of people getting ratelimited with the library

#

Though you're right, it is built in

slate swan
#

for adding roles you don't get rate limited. the lib handles the limit and just queues up the rest.

#

so technically you do and you dont lmao.

sick birch
#

Yeah. If you'd like, add a delay between each request. You don't have to

cobalt crane
#

So this code works, but how would I save just the attachment as a variable ?

await message.channel.send(file=await msg.attachments[0].to_file())
slate swan
#
image = await msg.attachments[0].to_file()
cobalt crane
#

If I use this it just sends the token of it. Like <discord.File object at...>. This is what Im doing :

image = await msg.attachments[0].to_file()
await message.channel.send(image)
slate swan
#

you need to await message.channel.send(file = image)

primal token
slate swan
#

the dpy library handles it tho

#

and when it is supposed to get rate limited it will just queue the rest

primal token
#

That doesnt mean you dont get ratelimited?

so technically you do and you dont lmao.
Quite contradicting

slate swan
#

not really lol

#

dont be weird

primal token
primal token
slate swan
#

??

slate swan
slate swan
# slate swan ??

wrong reply lol. but just check if the members status is idle and return a message if so

slate swan
slate swan
primal token
slate swan
slate swan
#

if message.mention()?

#

or like how would i do that

#

if message has message
Do functioon
else
pass

#

message.mentions() returns a list of user(s) if any

#

are you using dpy?

#

pycord

#

i would assume it just returns an empty list if no one is mentioned so you could

mentions = message.mentions
if not mentions:
    ....
#

how would i get the id of the person who was pinged?

#

iterate through mentions for the members and member.id

#

how though, my brain dead as fuck

cobalt crane
#

Anyone know how I can use pytesserect with a file the user sends? I'm able to get the file into a varible now but it brings the "unsupported file type" error now. It works with a normal file that but it wont with the one saved from discord.
Heres my code:

image = await msg.attachments[0].to_file()

test = pytesseract.image_to_string(image)
await message.channel.send(f"***The text in the image says***:\n {test}")
rare echo
#

you could just check if message.content contains the user id

slate swan
#
for member in mentions:
rare echo
#

or that

silk fulcrum
slate swan
silk fulcrum
#

PIL is dead isnt it?

slate swan
#

idk lmao. thats one the examples for the pytesseract lib he is using lol

slate swan
slate swan
silk fulcrum
#

!d discord.Message.mentions

unkempt canyonBOT
#

A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.

Warning

The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.

primal token
silk fulcrum
slate swan
#

an empty list returns false

primal token
#

Its an attribute not a method, you cant call it as it would raise list object is not a callable blah blah blah

slate swan
#

fixed it

silk fulcrum
#

oh he called it bruh

#

what does if not mentions: ... mean tho? Are you trying to do something if there are no mentions?

#

I can't imagine a reason to need that

slate swan
#

that means the list isn't empty lol

#

so you can continue

#

to do what is needed

silk fulcrum
#

if not mentions: literally checks if a list is empty

#

or that ... means end the process?

slate swan
#

wait

#

my brain exploding rn

#

lmfao

primal token
#

!e

if not []:
    print(1)
unkempt canyonBOT
#

@primal token :white_check_mark: Your 3.11 eval job has completed with return code 0.

1
silk fulcrum
#

:lmao:

primal token
#

its syntax is

if True:
    ...
if not True:
    ...
slate swan
# slate swan ```py for member in mentions: ```

heres what i have
mentions = message.mentions()
for member in mentions:
id = member.id
with open('assets/afk/afkusers.json', 'r') as f:
afk = json.load(f)
if not afk in afk:
pass
await ctx.respond("This user is afk! Please wait.")

it returns this
TypeError: 'list' object is not callable

#

yeeee

silk fulcrum
#

that's what you were typing

slate swan
#

message.mentions noid caught it

#

don't call it.

slate swan
#

remove ()

slate swan
silk fulcrum
silk fulcrum
slate swan
#

open the file first

#

before the loop

silk fulcrum
#

i don't even know what you are doing from this code

#

its so confusing

slate swan
#

he is checking for afk members in a message

#

if message contains a mention and that member is afk then do stuff

silk fulcrum
#

that if not afk in afk: pass does just literally nothing

slate swan
#

meant to be afk

#

i mean id

silk fulcrum
#

if any(m.id in afk_list for m in mentions)

#

will check if any user that is mentioned is afk

#

if you need to know which user(s) is(are), then you would need a loop

slate swan
#

how would i define m or member

silk fulcrum
#

wdym

slate swan
#

how would i continue my function after dat

#

i need to get the mentioned persons id

silk fulcrum
#
if any(m.id in afk_list for m in mentions):
    await ctx.respond("This user is afk! Please wait.")```from you previous code ig this is what you wnat
silk fulcrum
#

why tho?

slate swan
#

cause in the json file

#

its id and if they are afk or not

#

so i nedd to get if there is a mention in a message, and the mentioned persons id

silk fulcrum
#

how does it look like?

slate swan
#

the .json?

silk fulcrum
#
{
    234598765432: "afk",
    345987656787: "not afk",
}``` like this?
slate swan
#

somewhat

#

does the same thing

#

if they go afk it changes the 0 to a 1

silk fulcrum
#

ok

slate swan
#

and when they get mentiond, it looks to see if they are afk

silk fulcrum
#
if any(afk_list[str(m.id)]["afkstatus"] == 1 for m in mentions):
    await ctx.respond("This user is afk! Please wait.")```then it would be this
#

(afk_list is the content you read from json)

primal token
silk fulcrum
#

sad

primal token
#

Nice statementpithink

silk fulcrum
#

im just so addicted to databases

vale wing
#

Have you tried surreal db already

mental hollow
#

How do I use an if statement to check if the author is my bot owner? I tried this but it didn’t work:

if not ctx.author.is_owner():
    return await ctx.send("not owner")
else:
    await ctx.send("owner")
potent spear
tawdry adder
#

hello

#
bot = commands.Bot(command_prefix='>', intents = discord.Intents.message_content, discord.Intents.message_content = True)

why this Intents arent possible to do so?

vernal plinth
tawdry adder
#

and if i want in 1 line?

vernal plinth
#

god youre so unorganized

#

i dont think its possible

#

unless
discord.Intents.default().message_content = True

tawdry adder
#

im prefectzionism

#

lol

vernal plinth
tawdry adder
#

that didnt work lol

#

nvm

slate swan
#
(intents:=discord.Intents.default()).message_content = True
bot = Bot(..., intents  = intents)
``` maybe
slate swan
slate swan
slate swan
#

why are you using discord.BotIntegration?

slate swan
#

?

#

I copied paste

#

ok, but initially why were you using it?

slate swan
#

boost bot

#

bot = commands.Bot(command_prefix="!", intents=intents)

#

replace

slate swan
#

solved that one

#

pasted off github?

slate swan
#

well then it might not work

#

I'm beginner

#

idk much about python

#

I'm just learning

#

ok

slate swan
#

outdated

slate swan
#

@slate swancan you please tell me why this attribute error comes often

slate swan
vale wing
# slate swan I'm just learning

If your goal is to learn python, I don't recommend starting from discord bots, that's way too complicated thing for beginners

slate swan
#

how do i make it that my sends exactly what someone says

#

its a varation of on message right?

vale wing
glad cradle
vocal snow
#

Or Intents._from_value(...)

slate swan
#

Traceback (most recent call last):
File "main.py", line 11, in <module>
bot = discord.Bot(intents=discord.Intents.all())
AttributeError: module 'discord' has no attribute 'Bot'

#

who can help ?

vocal snow
slate swan
#

py-cord

#
pip install git+https://github.com/Pycord-Development/pycord ```
#

ig

vocal snow
#

can you run pip show py-cord?

slate swan
#

its work done u just need to do pip install git+https://github.com/Pycord-Development/pycord

#

thx

ionic edge
#
    @commands.Cog.listener()
    async def on_message(self, message):
        if message.author.bot:
            return
        cursor = self.client.db.cursor()
        cursor.execute(f"SELECT * FROM afk WHERE user_id = {message.author.id} AND guild_id = {message.guild.id}")
        result = cursor.fetchone()
        if message.author.id in result[0]:
            cursor.execute(f"DELETE FROM afk WHERE user_id = {message.author.id} AND guild_id = {message.guild.id}")
            await message.channel.send(f"**{message.author.name}#{message.author.discriminator}**, You are no longer AFK.")
            self.client.db.commit()
        for result in cursor:
            member = discord.utils.get(message.guild.members, id=result[0])
            if(message.reference and member ==(await message.channel.fetch_message(message.reference.message_id)).author) or member in message.raw_mentions:
                await message.reply(f"**{member.name}#{member.discriminator}** is AFK from (<t:{result[3]}>)")
        ```
bright wedge
robust fulcrum
#

Guys i have this named tupleuser(item=[(12345,"hi),(12345,"hi"),(12345,"hi")])
How can I display the name"hi" in the embed and how many times it is in list or tuple?

ionic edge
robust fulcrum
#

@ionic edge i have once made a afk comamnd do you want see it and have some idea?

bright wedge
#

aiosqlite?

ionic edge
#

sqlite

robust fulcrum
bright wedge
#

try something like that

robust fulcrum
#

@ionic edge don't use f string in the query

bright wedge
#
            async with aiosqlite.connect(f'your database') as db:
                async with db.execute("SELECT * FROM afk WHERE user_id = ? AND guild_id = ?", (message.author.id,message.guild.id,)) as cursor:
                    result = await cursor.fetchone()
robust fulcrum
#

Ye place holder is correct way

bright wedge
#

this is the async wait using aiosqlite

ionic edge
bright wedge
#

if you have connect your db, you dont need the first line

robust fulcrum
bright wedge
robust fulcrum
#

@ionic edge https://paste.pythondiscord.com/zopibedapo

And don't use f string in the SQL query use place holder
You can search google for it
Don't think i am saying you to copy my comamnd code
Just get some idea from it
Implement your own

dawn shard
robust fulcrum
#

@rugged shadow bro yesterday you helped me at level system but their's problem in that

ionic edge
dawn shard
#

ok

zealous jay
#

In the query

tawdry adder
#

how do you import another file?

#

like i have config.json and bot.py

ionic edge
#

wdym?

tawdry adder
#

i have json file with TOKEN

#

i want to use the TOKEN from another JSON file

#

import 'config.json' says its wrong

slate swan
#

If I wanted to make a bot that when a message is sent, a week later or checks if it has 5 reactions

#

How would I go about doing that? Wouldn't waiting that long halt everything? Is AsyncIo the way to go?

cold sonnet
#

not really, I mean particularly yes, but not in the way you think
the best way would be to save dates when a message should be checked in a database and have a task running to check if a date has passed and then check the message

#

because with asyncio.sleep(), you're gonna lose a week of data after every restart

tawdry adder
#

how do i print "Error" when i type <PREFIX>cls and the count is none?

wicked atlas
# tawdry adder

give it a default value

async def clear(ctx, num: int = None):
#

an maybe move that purge statement into an else statement

#

Otherwise you might end up with errors or unwanted behavior

slate swan
#

hi

sick birch
#

Hi

ionic edge
#

how to create it ??

slate swan
ionic edge
slate swan
unkempt canyonBOT
#

discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") for presentation within Discord.

This allows for a locale-independent way of presenting data using Discord specific Markdown...
primal token
#

it's num: int | None = None

maiden fable
unkempt canyonBOT
#

discord/ext/commands/core.py lines 686 to 690

if param.required:
    if self._is_typing_optional(param.annotation):
        return None
    if hasattr(converter, '__commands_is_flag__') and converter._can_be_constructible():
        return await converter._construct_default(ctx)```
wicked atlas
#

You can typehint a parameter as Optional and it'll set it to None as default if it's not provided

primal token
wicked atlas
#

Looks like you can do it with | None as well

maiden fable
#

So that u don't have to do the ugly = None

primal token
#

Default values aren't ugly smh

maiden fable
#

None seems hella ugly to me to be honest ĀÆ_(惄)_/ĀÆ

primal token
#

So you want null?

maiden fable
#

I prefer default values to None as default values, like time: int = 5 instead of time: int = None and then using an if statement

vocal snow
#

typecheckers would swear at you for the latter

maiden fable
#

Bro

vocal snow
#

you're saying it's an int and then setting to None, wtf

maiden fable
#

Feel what I am tryna say, don't go on my code its rusty

primal token
#

see zeffo agrees

primal token
vocal snow
maiden fable
#

-.-

primal token
slate swan
#

šŸ‰

primal token
#

i had a discussion about it in #type-hinting and iirc most linters didnt care abour default values with different types and the types not being specified

vocal snow
#

pylance does !

slate swan
primal token
primal token
slate swan
#

no

maiden fable
primal token
#

šŸ‘€

slate swan
#

yes, I'm not now python smh

#

don't know*

primal token
#

ok

slate swan
#

oh hi okimii

maiden fable
#

Smh don't start this again

slate swan
#

lmao

#

can somebody help me create a command for a bot

#

i barely know anything about python

#

learn it

maiden fable
#

!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.

primal token
slate swan
#

random?

#

thanks

maiden fable
primal token
#

Who made this? Its horribly written

maiden fable
#

Dude

primal token
#

What

slate swan
#

the command i am looking for is to give coins to an other user

#

i want to make a shop server

#

with its own currency

primal token
#

And most importantly which i always see is people not knowing about polymorphism

maiden fable
#

I mean, there is no harm in saying that, not everyone is as good in english as u r and many people have English as their secondary language

wicked atlas
#

yeah, not everyone can spot spelling/grammar mistakes in messages two seconds after being sent

slate swan
#

I'm not even gonna comment since noid is quite annoying as usual.

#

no hate lmao

primal token
maiden fable
#

not everyone is as good in English as u r, so imho that gist is right in specifying it as methods rather than using those terms ĀÆ_(惄)_/ĀÆ

primal token
#

Not really terms, they're import principles of OOP

#

So if you learn OOP you should also know about them

maiden fable
#

methods are part of the oops, and that is the term people use in daily usage. They don't just go on and say encapsulation. I mean, I have never seen anyone use those terms apart from u, not even anyone from dpy server or even this server

slate swan
#

same tbh

primal token
#

Encapsulation isnt methods only!

vocal snow
slate swan
maiden fable
primal token
primal token
#

I would say it's a quite nice thing to do, especially for people who want to learn about a topic

wicked atlas
#

Well, to go back to your first statement, I wouldn't say it's horribly written, just not written to your high standards

primal token
#

From what i read, it still was poorly written

red onyx
#

I've tried 1000 times but I don't know how can anyone send me a discord bot code where It can send 4 difrent responses to 4 difrent questions?

bright wedge
#

hello is there anyone can join on my server (im testing something, a new game) its a card game!

pulsar solstice
#

will if user1 == discord.Member: check if the user1 object is a member object?

wicked atlas
maiden fable
red onyx
wicked atlas
pulsar solstice
maiden fable
#

That too

maiden fable
#

Sorry, then AM2i9 told u!

wicked atlas
pulsar solstice
wicked atlas
#

!d isinstance

unkempt canyonBOT
#

isinstance(object, classinfo)```
Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") exception is raised.

Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union).
primal token
drowsy path
#

OCR Land is a theme aimed at children and adults. Entrance tickets are sold online. An adult ticket to OCR Land costs £19.99, with a child ticket costing £8.99. A booking fee of £2.50 is added to all orders. A function, ticket price(), takes the number of adult tickets and the number of child tickets as parameters. If calculates and returns the total price to be paid.

Use pseudo code to create a algorithm for the function ticket price ()

shell wing
#

I have a welcome event...how can i make so that the bot sends message only when a user joins a specific server...not all the servers the bot is there...

pulsar solstice
drowsy path
#

Can someone help

slate swan
#

exenifix šŸ’€ wtf

drowsy path
#

?

#

Can someone help me

primal token
vale wing
#

What's pound of sterlings to rubles course

#

I wanna buy those tickets

primal token
#

Its an exercise so no tickets😦

vale wing
#

Sad

shell wing
slate swan
#

if member.guild.id == ...: #do stuff

#

or do the opposite and add a return so you don't gotta worry about indentation huh

shell wing
#

ah alr

red onyx
#

I've tried 1000 times but I don't know how can anyone send me a discord bot code where It can send 4 difrent responses to 4 difrent questions?

red onyx
#

1001 tbh

bright wedge
#
class Dropdown(discord.ui.Select):
    def __init__(self):
        options = [
        for i in players_list:
            discord.SelectOption(label='Donate', emoji='šŸ’ø'),                
        ]

hey i can add somehow dropdown option using loop? (i will do some changes in list so i need more/less option in my dropdown!)

sick birch
bright wedge
#

here?

sick birch
#

Yes

bright wedge
#

add_item() accept class right?

#

or i can create the option in add_item?

sick birch
bright wedge
# sick birch It takes a class
class DropdownView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)

        self.add_item(discord.SelectOption(label='Test', emoji='šŸ’ø'),)
#

something like that? in for loop?

sick birch
#

You need to add a Select object not SelectOption

bright wedge
astral ether
#

hello I'm new to discord.py and I can't send a message with an embed can someone help me?

@bot.event
async def on_messages(message):
    if message.content.lower() == 'test':
        test = discord.Embed(colour=None, color=0x3498db, title='test', type='rich', url=None, description='test', timestamp=None)
        await message.channel.send(embed=test)
hushed galleon
#

also worth mentioning to make sure you have the message_content intent enabled in your code

bright wedge
#
class VoteMenu(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)
        for i in range(3):
            self.add_item(discord.ui.Button(label=f"{i}", custom_id=str(i)))

now how i can use the custom_id for add an action in button?

#

using callback?

hushed galleon
#

yup, its still with callbacks

bright wedge
# hushed galleon yup, its still with callbacks
class VoteMenu(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)
        for i in range(3):
            self.add_item(discord.ui.Button(label=f"{i}", custom_id=str(i)))

    async def callback(self, interaction: discord.Interaction):
        if self.values[0] == "1":
            print("helo")

something like that?

hushed galleon
#

you have to specify the callback on your button objects

#

in your case inheritance would be the preferred way to do so

#

i.e. ```py
class VoteButton(discord.ui.Button):
async def callback(...):

inside VoteMenu

self.add_item(VoteButton(label=f"{i}", ...))```

bright wedge
hushed galleon
#

no you'd put the callback method in a separate Button subclass as per my example

bright wedge
#

i dont got you...

hushed galleon
#

there's two different classes you would have, a VoteButton and a VoteMenu

astral ether
hushed galleon
#

the VoteButton is where you'll write the async def callback, and the VoteMenu is where you'll add your three VoteButton objects

bright wedge
#
class VoteMenuButtons(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)

    @discord.ui.button()
    async def options(self, interaction: discord.Interaction, button: discord.ui.Button):
        if button.custom_id == "1":
            print("hello")


class VoteMenuView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)
        for i in range(3):
            self.add_item(discord.ui.Button(label=f"{i}", custom_id=str(i)))
bright wedge
#

can i get a good example please?

slate swan
#
class VoteButton(ui.Button):
  def __init__(self) -> None:
    super().__init__(...)
  
  async def callback(self, interaction: discord.Interaction) -> None:
    ...

class VoteView(ui.View):
  def __init__(self) -> None:
    self.add_item(VoteButton())

is this what you're looking for, from what I've inferred from your conversation

hushed galleon
#

also another example similar to ashley's: ```py
class MyButton(discord.ui.Button):
async def callback(self, interaction):
await interaction.response.send_message(f'You clicked {self.label}!')

class MyView(discord.ui.View):
def init(self):
super().init()
for label in ('sharex', 'foobar2000', 'vlc'):
self.add_item(MyButton(label=label))```

#

see the pattern? two classes, one inheriting from Button, the other inheriting from View

hushed galleon
#

sure

bright wedge
#

how?

hushed galleon
#

depends on what guild you need the view to know about...?

#

for example if it needs to know the current guild, you might make it a parameter of init and pass it during instantiation

#
class MyView(discord.ui.View):
    def __init__(self, guild: discord.Guild):
       super().__init__()
       self.guild = guild

@bot.command()
async def mycommand(ctx):
    view = MyView(ctx.guild)
    ...```
bright wedge
#

ok i got you

hushed galleon
#

this is mostly object oriented programming, whatever concepts and techniques you can use with regular classes also apply to discord.py's views

swift pumice
#

OK

#

Hi

primal token
#

I would say that's an exaggeration

vocal snow
#

Okimii learning about hyperboles

primal token
#

I doubt hes learning about hyperboles, either way its a topic you learn in 5th grade

white citrus
#
Traceback (most recent call last):
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 502, in _run_event
    await coro(*args, **kwargs)
  File "c:\Discord\Maja Projekt\MajaSystem\bot.py", line 220, in on_application_command_error
    raise error
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 863, in invoke_callback_with_hooks
    await self(interaction, *args, **kwargs)
  File "c:\Discord\Maja Projekt\MajaSystem\modules\beta_features\cog.py", line 31, in repo_bug
    await dev_server.send(embed=dev_embed)
AttributeError: 'NoneType' object has no attribute 'send'```
#
    @nextcord.slash_command(name="report-bug", description="Report a Bug")
    async def repo_bug(self, interaction: nextcord.Interaction, message: str = SlashOption(name="message", description="Please describe your problem or the error",
                                                                                           required=True, max_length=250)):
        dev_server = interaction.client.get_channel("1024019062558314537")
        
        random_id = random.randint(1_000_000_000, 9_999_999_999)
        dev_embed = nextcord.Embed(title=f"Report from {interaction.guild.name}",
                                   description=message)
        dev_embed.add_field(name="Please answer tot the following ID:", value=interaction.channel.id)
        dev_embed.add_field(name="Case ID", value=random_id)
        
        await dev_server.send(embed=dev_embed)
        await interaction.response.send_message(content="Thank you for your report. The team will take care of it as soon as possible and send you an answer in this channel.", ephemeral=True)
        ```
astral ether
#

hello, I want to make a bot, but there is a function I don't know what it's called, this function is a message sent by the bot, and clicking on it puts a list where you can choose roles for example

glad cradle
slate swan
#

how i can make this command?

primal token
slate swan
#
@commands.slash_command()
    async def timeout(self, ctx, member: disnake.Member):
        await member.edit(timeout = datetime.timedelta(hours = "1"))```
primal token
astral ether
feral frost
#

guys

#

how do i use a def check(message): for a number

#

just a random number

primal token
#

It still applies, but the given method is incorrectšŸ˜…

rapid knoll
#

how do I find a ctx's role?

maiden fable
primal token
maiden fable
#

Conversion to the typehint

primal token
#

I'm not referring to the conversion of arguments

maiden fable
#

Then?

primal token
#

i'm referring to

discord.Client.get_channel

which doesnt raise a TypeError when the incorrect type is passed as an argument

maiden fable
#

Ohh wait, u meant convertung the string to type int

primal token
#

Yes!

feral frost
#

Code:

def check(message):
            return message.author == ctx.author and message.channel == ctx.channel and message.content.lower() == "close"```
**Question:**
How can i make it so the "close" will be the message i input and that the bot will print in the output ?
maiden fable
#

Ngl that's a mystery to me too. Probably cz Danny loves IDs as ints only and hates it when someone uses strings? Who knows 🫤
At least u can use a string type ID in fetch methods

glad cradle
sick birch
primal token
maiden fable
#
maiden fable
glad cradle
feral frost
maiden fable
#

That's correct. That if statement checks the whole message and not a part of it, so the check won't pass if u send anything other than just the word close in yr message @feral frost

feral frost
maiden fable
#

Uh what? @primal token do you mind helping Mimmeke with their issue? I gotta crash, it's late here

glad cradle
wicked atlas
feral frost
#

yes

#

that can work

#

it does thanksu

maiden fable
wicked atlas
#

ĀÆ_(惄)_/ĀÆ

maiden fable
#

I'm just confused, so correct me if I'm wrong lol

astral ether
astral ether
glad cradle
#

btw to send a view you need to first create a view

#

so in the example it create first a view with some basic things and then send it

astral ether
shut tendon
#

Hey guys I have no clue why my bot is not replying to my command, I activated all the intents within the code and on dev side. Here's the code ```
import discord
from token_bot import bot_token
from discord.ext import commands

intents = discord.Intents.all()

bot = commands.Bot(command_prefix="$", description="Hey there, I'm a bot :)", intents=intents)
client = discord.Client(intents=intents)

@client.event
async def on_ready():
print(f"We have logged in as {client.user}")

@bot.command()
async def test(ctx, arg):
await ctx.send(arg)

'''@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith("$hello"):
await message.channel.send("Hello!")'''

client.run(bot_token) ```

glad cradle
feral frost
feral frost
primal token
#

That expression seems a bit redundant in my opinion

feral frost
#

not my intentions

wicked atlas
#

@feral frost if you want to check if a string is all lowercase, just use islower()

message.content.islower()
feral frost
#

ok

astral ether
slate swan
#

How to add a file on a webhook with requests?

glad cradle
wicked atlas
astral ether
#

thanks šŸ˜…

slate swan
wicked atlas
# wicked atlas With requests, you can use the `file` argument to send a file

@slate swan You'd have to do something like

request.post(url, files={"myfile.txt": open('myfile.txt', 'rb')})

But if you want to send a JSON object with other information, you need to send it with something like this, since the body will be form data

request.post(url, files={
    "myfile.txt": open('myfile.txt', 'rb'),
    "payload_json": (None, json.dumps(data))
})
glad cradle
wicked atlas
#

theres also a few more things, such as the fact you have bot a bot and a client, you should only have one, and that you don't actually enable message content intents

white citrus
#
Traceback (most recent call last):
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 502, in _run_event
    await coro(*args, **kwargs)
  File "c:\Discord\Maja Projekt\MajaSystem\bot.py", line 220, in on_application_command_error
    raise error
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 863, in invoke_callback_with_hooks
    await self(interaction, *args, **kwargs)
  File "c:\Discord\Maja Projekt\MajaSystem\modules\beta_features\cog.py", line 48, in answer_to_request
    await answer_channel.send(embed=ae)
AttributeError: 'NoneType' object has no attribute 'send'```
#
    @nextcord.slash_command(name="answer-to-request", description="Answer to a request")
    async def answer_to_request(self, interaction: nextcord.Interaction, content: str = SlashOption(name="content", description="Please type here your answer",
                                                                                           required=True, max_length=200),
                                ac: int = SlashOption(name="channel_id", description="Please type here the ID from the Report Channel", required=True)):
        
        if interaction.user.id == 881929560059428924:
        
            answer_channel = interaction.client.get_channel(ac)
            
            ae = nextcord.Embed(title="You got an answer from the Maja Bot Dev Team", description=f"{config.DiscordSupport} {content}")
            
            await answer_channel.send(embed=ae)
            await interaction.response.send_message(content="Your reply has been sent successfully", ephemeral=True)
            
        else:
            await interaction.response.send_message(content="You can not use this command. You are not a member of the Maja Bot Dev Team.", ephemeral=True)
        ```
rapid knoll
#

how do I get the bot to check if the user has reacted with a certain role?

shut tendon
wicked atlas
weary flume
#

is there a way to prevent members from typing more than 3 lines with a bot?

white citrus
wicked atlas
#

ah, alright then

#

get_channel attempts to get the channel object from it's internal cache. If it's not in there, it returns None. You can fix it by doing something like this to fetch the channel with an API call if it's not in the cache

answer_channel = interaction.client.get_channel(ac) or await interaction.client.fetch_channel(ac)
bright wedge
#
            if self.custom_id == "0":
                embed.add_field(name=interaction.message.embeds[0].fields[0].name, value=int(interaction.message.embeds[0].fields[0].value)+1,inline=False) ## here
                embed.add_field(name=interaction.message.embeds[0].fields[1].name, value=interaction.message.embeds[0].fields[1].value,inline=False)
                embed.add_field(name=interaction.message.embeds[0].fields[2].name, value=interaction.message.embeds[0].fields[2].value,inline=False)
                embed.add_field(name=interaction.message.embeds[0].fields[3].name, value=interaction.message.embeds[0].fields[3].value,inline=False)
                embed.add_field(name=interaction.message.embeds[0].fields[4].name, value=interaction.message.embeds[0].fields[4].value,inline=False)
                embed.add_field(name=interaction.message.embeds[0].fields[5].name, value=interaction.message.embeds[0].fields[5].value,inline=False)

            if self.custom_id == "1":
                embed.add_field(name=interaction.message.embeds[0].fields[0].name, value=interaction.message.embeds[0].fields[0].value,inline=False)
                embed.add_field(name=interaction.message.embeds[0].fields[1].name, value=int(interaction.message.embeds[0].fields[1].value)+1,inline=False) ## here
                embed.add_field(name=interaction.message.embeds[0].fields[2].name, value=interaction.message.embeds[0].fields[2].value,inline=False)
                embed.add_field(name=interaction.message.embeds[0].fields[3].name, value=interaction.message.embeds[0].fields[3].value,inline=False)
                embed.add_field(name=interaction.message.embeds[0].fields[4].name, value=interaction.message.embeds[0].fields[4].value,inline=False)
                embed.add_field(name=interaction.message.embeds[0].fields[5].name, value=interaction.message.embeds[0].fields[5].value,inline=False)
#

how i can make this looks better

#

im trying to edit a embed value

#

if self.custom_id == "0": im changing the first field only
if self.custom_id == "1": im changing the second one only
i want the others fields the same, i mean if i change the first field the other 5 not change.
etc.

wicked atlas
#

could do something like

n = 0 # or 1, or 2, or whatever
for i, field in interaction.message.embeds[0].fields:
    value = field.value
    if i == n:
        value = int(field.value)
    embed.add_field(name=field.name, value=value)
wicked atlas
#

Or, if the new embed and the old one are the same except for that one value, just modify the old embed

wicked atlas
tawdry adder
#

what about this error please>?

wicked atlas
#

print is not an async function, you don't need to await it

tawdry adder
#

lol im stupid sry

#

my bad

#

and is there like a delay command if i want to wait a bit between print-s

glad cradle
#

replace seconds with an int

tawdry adder
#

thankssss

glad cradle
wicked atlas
white citrus
wicked atlas
#

😦

bright wedge
#

@wicked atlas is top šŸ” ā«

tawdry adder
wicked atlas
glad cradle
white citrus
tawdry adder
white citrus
#

And nextcord.Channel doesnt exists

wicked atlas
#

And did you scroll up and see what message I was replying to, or just assumed it was my first reply?

white citrus