#discord-bots

1 messages ยท Page 121 of 1

whole sparrow
#

Can I add a picture in an embed thats above the description text?

cerulean folio
whole sparrow
#

thats a thing?

cerulean folio
#

and they'll be in one single message

whole sparrow
#

Not sure if im understanding, how would you add an embed to the same embed in the first place. It sounds really interesting though

slate swan
cerulean folio
whole sparrow
#
embeds = discord.Embed()
embeds.append(discord.Embed(color = your_color, description=your_description))
await inter.send(embed=embeds)
#

Like this?

slate swan
#

nah embeds needs to be a list

#

also that is just creating 2 seperate embeds

whole sparrow
slate swan
#

embeds = embeds

cerulean folio
whole sparrow
#

youre a legend im going to try that out

slate swan
#

embed only takes a single embed

cerulean folio
#

right sorry

steel geyser
#

import discord
from discord.ext import commands
import random

TOKEN = 'TOKEN'
prefix = commands.Bot(command_prefix='/')

client = discord.Client()

@client.event
async def on_ready():
print('hello')

@client.event
async def on_message(ctx):
await ctx.send('Hello')

prefix.run(TOKEN)

cerulean folio
whole sparrow
#

xd yeah

steel geyser
whole sparrow
#

Yup that works, sends 2 embeds in the same message

#

thanks

cerulean folio
cerulean folio
#

now when you run /hello it should show

steel geyser
#

ok thanks

slate swan
slate swan
primal token
#

And it must listen to events, right now you aren't listening to anything and your code will raise an attribute error

cerulean folio
#
@client.event
async def on_ready():
    print('hello')

@bot.command(name='hello')
async def on_message(ctx):
    await ctx.send('Hello'

this works

slate swan
#

anyone know of a way to get the user who invited your bot to the guild that doesn't require 'dangerous' server permissions e.g audit log access?

slate swan
slate swan
#

tears i really dislike dpy's event handling for the same reason

#

name based events

steel geyser
#

is it the prefix?

slate swan
cerulean folio
cerulean folio
# steel geyser oh ok lol

also add intents to your bot like so:

bot = commands.Bot(command_prefix = '/',
                   intents = discord.Intents.all())

and it should stop that error message tho

steel geyser
#

thx

verbal monolith
#

yo so if i dont want my bot to send in a channel, it would be like py if message.channel.name != 343944376055103488: right?
and if its multiple then it would be py blocked_channels = '343944376055103488, 813178633006350366' if message.channel.name != in blocked_channels:
right?

glad cradle
verbal monolith
#

sooo

glad cradle
#

if message.channel.id != id: ...

verbal monolith
#

and is there a more efficient way to do it

glad cradle
#
if message.channel.id not in (id1, id2, id3, ...):
    # do something
verbal monolith
glad cradle
#

what

verbal monolith
#

like

#

they do the same, but not in is better?

glad cradle
#

they are not the same thing, also != in is invalid syntax

verbal monolith
#

oh, how so ?

#

oh i see

#

i just saw it

#

ok thank u sm

primal token
glad cradle
#

!= means not equal to
in means sequence with a specified value is inside the object

#

in wording is not mine

primal token
#

You can of course override the dunder and do some weird stuff

#

!e

class Foo:
    def __contains__(self, item: "Any") -> None:
        print(item)

1 in Foo()
unkempt canyonBOT
#

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

1
glad cradle
primal token
#

๐Ÿ‘

glad cradle
cerulean folio
#
msg = await bot.wait_for('message', check=check)

I'd like to pass ctx inside the check

#

how can i do it?

primal token
#

Why?

slate swan
cerulean folio
slate swan
#

or use a lambda if its not too long

primal token
#

The method returns the message object, if listening to a message, so if you're going to compare authors you can always compare them from the caller

slate swan
primal token
#

Thats an interesting way non the less

cerulean folio
slate swan
#

quite fun to use

mighty pilot
#

Something else I was looking for a while back but never found so I worked around it pikafacewow

south coyote
#

can somebody help real quick. should be easy. i just can't figure it out. where would i put this...

async def foo():
    async with aiohttp.ClientSession() as session:
        webhook = Webhook.from_url('url-here', session=session)
        await webhook.send('Hello World', username='Foo')

in this...

https://github.com/grasshaussoftware/support-bot-piphi/blob/main/bot_2.py

GitHub

support bot for https://piphi.network discord server - support-bot-piphi/bot_2.py at main ยท grasshaussoftware/support-bot-piphi

#

im trying to send a notification to a webhook when a new ticket is created

mighty pilot
#

Is there any part of your code that you haven't needed help with? Seems like you've been in here for days

south coyote
#

i know. i have been

sick birch
#

but that's why we're here, eh?

mighty pilot
#

Yea I mean at least it's something that's not super basic

sick birch
#

I'm always glad to help anyone, so long as it's not something that can easily be solved with a little research C:

south coyote
#

ive looked up and down

#

thanks robin

sick birch
#

Any errors? What happens when you call the function?

south coyote
#

no errors

#

it just doesn't send the notification

#

everywhere i put it

sick birch
#

Try a print statement inside of the function to see if it's being called

south coyote
#

ok

#

i can't figure out where to call it from

#

wait

mighty pilot
#

And learning from other people's errors

south coyote
#

can i do this....

await interaction.send(f"I've opened a ticket for {user.mention} at {channel.mention}!", ephemeral = True), foo()
#

put it at the end of the line?

sick birch
#

Just a simple print statement inside of foo() to see if it's being called

#
async def foo():
    print("Sending webhook notification...")
    async with aiohttp.ClientSession() as session:
        webhook = Webhook.from_url('url-here', session=session)
        await webhook.send('Hello World', username='Foo')
south coyote
#

but if its not being called anywhere...

sick birch
#

Of course it wouldn't send the webhook notification then

south coyote
#

okay so i gotta call it somehwere

#

preferably along with the ticket creation

#

i finally got some sleep last night

#

i was up for like two days i think

mighty pilot
#

Just working on this?

south coyote
#

yeah

mighty pilot
#

Nah I put sleep above everything

south coyote
#

im trying to impress some new friends

mighty pilot
#

Baby keeps me up too late, I call into work so I can sleep lol

sick birch
south coyote
#

progress...

/home/deusopus/Desktop/ticketing_bot.py:35: RuntimeWarning: coroutine 'foo' was never awaited
  await interaction.response.send_message(f"I've opened a ticket for you at {channel.mention}!", ephemeral = True), foo()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

slate swan
#

why u calling foo after sending? why not call before

#

also you need to await it, it's async

cloud dawn
#

Anyone know what the regex is for Discord's valid link format? Aka when they do embed it.

cloud dawn
slate swan
#

https lol

#

http

#

is what makes it embedded/highlighted

#

afaik

cloud dawn
#

Looks like it.

south coyote
#

so it calls main() here. should i put it in main()?

#

nm

#

that doesn't work

#

its not getting called robin

glad cradle
south coyote
#

so...

#

thanks btw

#
await channel.send(f"{interaction.user.mention} created a ticket for {user.mention}!", view = main())```
#

this needs to be sent to a webhook

#

i have the webhook function

#

called foo

south coyote
#

yes

#

i was doing this....

#
await interaction.send(f"I've opened a ticket for {user.mention} at {channel.mention}!", ephemeral = True), foo()
glad cradle
#

foo is a coroutine, you need to await it

await foo()
south coyote
#

yeah

#

now im getting this....

#

i awaited it

#

but it's not getting to it

glad cradle
#

what

south coyote
#

one sec

#

now im getting this

#
ERROR    discord.ui.view Ignoring exception in view <ticket_launcher timeout=None children=1> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='Create a Ticket' emoji=None row=None>
Traceback (most recent call last):
  File "/home/deusopus/.local/lib/python3.10/site-packages/discord/ui/view.py", line 425, in _scheduled_task
    await item.callback(interaction)
  File "/home/deusopus/Desktop/ticketing_bot.py", line 35, in ticket
    await foo()
  File "/home/deusopus/Desktop/ticketing_bot.py", line 108, in foo
    await webhook.send('Hello World', username='Foo')
  File "/home/deusopus/.local/lib/python3.10/site-packages/discord/webhook/async_.py", line 1726, in send
    data = await adapter.execute_webhook(
  File "/home/deusopus/.local/lib/python3.10/site-packages/discord/webhook/async_.py", line 176, in request
    async with session.request(
  File "/home/deusopus/.local/lib/python3.10/site-packages/aiohttp/client.py", line 1141, in __aenter__
    self._resp = await self._coro
  File "/home/deusopus/.local/lib/python3.10/site-packages/aiohttp/client.py", line 400, in _request
    raise RuntimeError("Session is closed")
RuntimeError: Session is closed
#

i guess it wants me to do foo(self)

#

now i get this....

#
Traceback (most recent call last):
  File "/home/deusopus/.local/lib/python3.10/site-packages/discord/ui/view.py", line 425, in _scheduled_task
    await item.callback(interaction)
  File "/home/deusopus/Desktop/ticketing_bot.py", line 35, in ticket
    await foo(self)
  File "/home/deusopus/Desktop/ticketing_bot.py", line 108, in foo
    await self.webhook.send('Hello World', username='Foo')
AttributeError: 'ticket_launcher' object has no attribute 'webhook'
glad cradle
south coyote
#

now ive got this...

#
Traceback (most recent call last):
  File "/home/deusopus/.local/lib/python3.10/site-packages/discord/ui/view.py", line 425, in _scheduled_task
    await item.callback(interaction)
  File "/home/deusopus/.local/lib/python3.10/site-packages/discord/ui/view.py", line 138, in __call__
    return self.callback(self.view, interaction, self.item)
TypeError: ticket_launcher.foo() takes 1 positional argument but 3 were given
#

ill show you

#
class ticket_launcher(discord.ui.View):
    def __init__(self) -> None:
        super().__init__(timeout = None)
        self.cooldown = commands.CooldownMapping.from_cooldown(1, 10, commands.BucketType.member)
    @discord.ui.button(label = "Create a Ticket", style = discord.ButtonStyle.blurple, custom_id = "ticket_button")

    async def foo(self):
                print("Sending webhook notification...")
                async with aiohttp.ClientSession() as session:
                    self.webhook = Webhook.from_url('https://discord.com/api/webhooks/..../....', session=session)
                await self.webhook.send('Hello World', username='Foo')
    ```
glad cradle
#

what args are you passing to call foo?

glad cradle
south coyote
#

self

slate swan
#

umm

#

in discord.py should functions have specific names?

#
import discord

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

client = discord.Client(intents=intents)
@client.event
async def on2_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('$hello'):
        await message.channel.send('Hello!')

@client.event
async def on_message(message):
    if message.content.startswith('$greet'):
        await message.channel.send('Say hello!')

        def check(m):
            return m.content == 'hello' and m.channel == message.channel

        msg = await client.wait_for('message', check=check)
        await message.channel.send(f'Hello {msg.author}!')

client.run('$$$$')
#

the function with on_message title is the one that works only

#

when I swap names the other works

#

have you looked at the docs?

slate swan
south coyote
#

yes

slate swan
#

maybe it did but I am dumb

slate swan
south coyote
#
ERROR    discord.ui.view Ignoring exception in view <ticket_launcher timeout=None children=1> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='Create a Ticket' emoji=None row=None>
Traceback (most recent call last):
  File "/home/deusopus/.local/lib/python3.10/site-packages/discord/ui/view.py", line 425, in _scheduled_task
    await item.callback(interaction)
  File "/home/deusopus/Desktop/ticketing_bot.py", line 58, in ticket
    await foo()
  File "/home/deusopus/Desktop/ticketing_bot.py", line 70, in foo
    await webhook.send('Hello World', username='Foo')
  File "/home/deusopus/.local/lib/python3.10/site-packages/discord/webhook/async_.py", line 1726, in send
    data = await adapter.execute_webhook(
  File "/home/deusopus/.local/lib/python3.10/site-packages/discord/webhook/async_.py", line 176, in request
    async with session.request(
  File "/home/deusopus/.local/lib/python3.10/site-packages/aiohttp/client.py", line 1141, in __aenter__
    self._resp = await self._coro
  File "/home/deusopus/.local/lib/python3.10/site-packages/aiohttp/client.py", line 400, in _request
    raise RuntimeError("Session is closed")
RuntimeError: Session is closed


slate swan
glad cradle
#

!d discord.ext.commands.Bot.listen

unkempt canyonBOT
#

@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready")

The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.11)").

Example...
slate swan
#

ohh

#

i mean you can but they both won't work

glad cradle
slate swan
#

so I need to put all the functionality in 1 function?

glad cradle
#

what no

#

Well if you want yes

#

it's better

slate swan
#
import discord

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

client = discord.Client(intents=intents)
@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('$hello'):
        await message.channel.send('Hello!')

@client.event
async def on_message(message):
    if message.content.startswith('$greet'):
        await message.channel.send('Say hello!')

        def check(m):
            return m.content == 'hello' and m.channel == message.channel

        msg = await client.wait_for('message', check=check)
        await message.channel.send(f'Hello {msg.author}!')

client.run('$$$$')
``` instead of this
#

this ```py
import discord

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

client = discord.Client(intents=intents)
@client.event
async def on_message(message):
if message.author == client.user:
return

if message.content.startswith('$hello'):
    await message.channel.send('Hello!')

if message.content.startswith('$greet'):
    await message.channel.send('Say hello!')

    def check(m):
        return m.content == 'hello' and m.channel == message.channel

    msg = await client.wait_for('message', check=check)
    await message.channel.send(f'Hello {msg.author}!')

client.run('$$$$')```

#

or what?

glad cradle
#

btw seems like you're trying to make commands, are you following an outdated tutorial?

south coyote
#

@glad cradle here is the github of my code right now

#

im trying to figure out where to call foo()

slate swan
south coyote
slate swan
#

someone here gave me this today

#

they said it's the best I think

south coyote
#

don't follow links from strangers

slate swan
#

when I asked for a tutorial

south coyote
#

haha

slate swan
glad cradle
slate swan
#

Umm

glad cradle
#

it already handles things for you

slate swan
#

do you have an up to date tutorial that I can read?

#

without bothering you with useless stuff

#

the docs have a decent bit of examples

#

okie

#

ty mate

glad cradle
#

intents is required now

slate swan
#

i mean its a direct link from their "stable" documentation so typical dpy

#

I am a bit confused

glad cradle
glad cradle
#

what's the problem

slate swan
glad cradle
slate swan
#

use disnake

#

lmao. updated guides, cool community, and lots of UPDATED examples and guides

slate swan
glad cradle
slate swan
#

oh so instead of putting into change logs its in a seperate table of contents listed under "Migrating to 2.0" lol

glad cradle
slate swan
#

okie

slate swan
#
import discord

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

client = discord.Client(intents=intents)
@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('$hello'):
        await message.channel.send('Hello!')


    if message.content.startswith('$greet'):
        await message.channel.send('Say hello!')

        def check(m):
            return m.content == 'hello' and m.channel == message.channel

        msg = await client.wait_for('message', check=check)
        await message.channel.send(f'Hello {msg.author}!')

from discord.ext import commands

bot = commands.Bot(command_prefix='$',intents=intents)

@bot.command()
async def test(ctx):
    await ctx.channel.send(f'Hello ! banana')
    

client.run('$$$')```
#

@slate swan

#

the last bit doesn't work

#

the bot command bit

#

the rest works tho why?

#

why u using client and bot?

#

just use bot

#

bot = commands.Bot
@bot.event

#

oh

slate swan
# slate swan bot = commands.Bot @bot.event

import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='$',intents=intents)

@bot.event
async def on_message(message):
    if message.author == bot.user:
        return

    if message.content.startswith('$hello'):
        await message.channel.send('Hello!')


    if message.content.startswith('$greet'):
        await message.channel.send('Say hello!')

        def check(m):
            return m.content == 'hello' and m.channel == message.channel

        msg = await bot.wait_for('message', check=check)
        await message.channel.send(f'Hello {msg.author}!')



@bot.command()
async def test(ctx):
    await ctx.channel.send(f'Hello ! banana')
    

bot.run('$$$$')```
#

the last bit still doesn't work

#

it's cause ur using on_message as well hold on

#

will read that

slate swan
#

you can

#

oh k I found the solution in the article

#

ty

#

yup np

#

I want to get someone's ID when they call a command

alpine cove
#

oh woops

#

!d discord.Message

#

!d discord.Message.author

unkempt canyonBOT
alpine cove
unkempt canyonBOT
#

property id```
Equivalent to [`User.id`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.id "discord.User.id")
alpine cove
#

there u go

alpine cove
#

and not on_message

mighty pilot
#

trying to salvage someone elses code for a welcome image bot when new members join. however, it was last updated over a year ago and its stuck trying to grab the joining members profile pic. the code uses pillow and the error im getting is that the pfp url is a string and thats not callable

#

also tried the pfp itself without the .url and that doesnt work

alpine cove
#

*changed

#

*dpy

mighty pilot
#

any docs on what i need to do?

alpine cove
mighty pilot
#

yea so i can put it on a background image

unkempt canyonBOT
#

property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset "discord.Asset") for the avatar the user has.

If the user does not have a traditional avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.display_avatar "discord.User.display_avatar").
alpine cove
#

it returns discord.Asset

#

which has a .to_file and a .read

#

and also ,url but u won't need that

mighty pilot
#

alright ill see if i can get that going. thanks

frozen rain
#

How do I install discord.py. Iโ€™ve tried pip install discord.py and python 3 -m install -U discord.Py in IDLE, and terminal but I keep getting syntax errors. Iโ€™m using MAC OS

sick birch
frozen rain
slate swan
#

that will give you the users avatar image then u can do whatever with it

mighty pilot
rare saddle
#

Can you please tell me what is the best regex for filtering youtube links?

slate swan
#

google

nocturne totem
#

i keep getting this error when i try to install discord

slate swan
frozen rain
nocturne totem
#

it says n thumbnail vs for mac

slate swan
frozen rain
nocturne totem
#

click download tab

nocturne totem
hushed galleon
#

@frozen rain @nocturne totem if either of you want to skip the build tools stuff, you can downgrade to python 3.10 which has prebuilt wheels for the dependencies listed in your error message

nocturne totem
slate swan
#

Download the tools first

#

What you installed was just an installer for it

frozen rain
#

after closer reading. I do not have the same error message as them.

slate swan
#

The build tools are like 6gb+

nocturne totem
slate swan
frozen rain
hushed galleon
#

i wouldnt know the specific instructions as i havent used python on mac

obtuse blaze
#

How can I make like a xp bar on a embed? that will fill depending on a variable? is there any exmaple that I could see?

pliant gulch
#

I think the command was xcode-select something maybe --install?

#

Or you can download it via the appstore

frozen rain
#

would it be better to do that or downgrade to python 3.10?

nocturne totem
#

it worked

#

thtanks @slate swan

pliant gulch
#

Well, you should've installed xcode a while back for Mac if you code (or at least that's my opinion)

#

I use it for some other stuff like my wm

#

I would just install xcode instead of downgrading

cerulean folio
#

Hi again guys !
How do you use unittest during your bot developpement?

pliant gulch
#

There are probably external libraries you can use to mock gateway events, but I would assume for unit testing you'd be mainly dispatching manually a mocked gateway event, such as await Bot.dispatch("message", <discord.Message>)

#

It's quite cumbersome and I don't really see the merit from unit testing your bot considering that you could just add checks into your code

unkempt canyonBOT
sick birch
#

if you look at our repo we use testing for our bots

cerulean folio
cerulean folio
sick birch
#

The Python Discord Organization

cerulean folio
#

Alright !

pliant gulch
cerulean folio
#

Thank you Robin !

pliant gulch
#

Unit testing in my eyes would make sense for utility methods or other helper methods

cerulean folio
pliant gulch
#

It's gonna be annoying

sick birch
pliant gulch
cerulean folio
#

Yeah actually I got hired as a python dev i'll start working in junuary or febuary, and till there i need to sharpen my skills a lot

frozen rain
pliant gulch
#

Yes

#

Xcode is just a dependency from what I see in your case

cerulean folio
pliant gulch
#

Well yea it would be good to remember the naming conventions but that's really all there is to pep-8 as of now

#

Your IDE already formats tabs -> 4 spaces

#

Your IDE already does indentation for you

#

Etc

frozen rain
#

are their any resources available to aid learning discord.py? If so what are they?

cerulean folio
#

Yes, and also good programming logic, and easy smart coding. Like I'm currently spending my time staring at this bit of my code, trying to make it shorter, smarter, simpler, my goal is that anyone could understand what it does by a single glance

def filter_user(ctx, message):
# Function that checks if a message contains an ID, a mention
# or the word 'cancel', and ignores reply mentions
    return (message.author == ctx.author 
            and message.channel.id == ctx.message.channel.id
            and not message.reference
            and (message.content - message.mentions == None
            or message.content.isdigit() 
            or message.content.lower() == cancel))

async def await_message(ctx, bot):
# Funcion that will wait for a filtered reply, return False if it is a
# cancel, user ID otherwise.
    user = None
    while user is None:
        message = await bot.wait_for('message', 
                        check=lambda message: filter_user(ctx, message)).content.lower()
        if message.content.lower() == cancel:
            return False
       
#

And I'm scared the day I start my work, collegues will mock me because I code bad HH_Shy

pliant gulch
#

Does message.content - message.mentions even work?

cerulean folio
#

I... didn't try it yet ngl

pliant gulch
#

Isn't that str - list[discord.User | discord.Member]

#

Which would error in my eyes as of now

#

Since these are of two different builtin types

#

Also your using cancel here as a name/variable, not a string literal which will have an undefined error

#

Should be content.lower() == "cancel"

cerulean folio
#

no it's a questionnaire, bot asks and awaits for a response that matches conditions, and if you write cancel it stops the questionnaire

pliant gulch
#

Oh you defined it else where

slate swan
#

yes unless cancel is a function it should be "cancel"

cerulean folio
#

ah yeah it should indeed lol

#

but it's a variable in the top

#

that isn't really smart indeed, it would be clearer with just "cancel"

pliant gulch
#

Also your check has an oversight when it comes to "id"s

#

You only check for isdigit not some 64 bit integer

#

So I could just pass 1 and it'll probably pass

cerulean folio
#

what if I then use soemthing like this:

async def check_id(bot, arg):
  try:
    await bot.fetch_user(arg)
    return True
  except discord.NotFound:
    return False

and check for await check_id(bot, message.content) ?

slate swan
#

i ain't gonna lie

pliant gulch
#

You could, but if you need the user | member object of the ID passed later I would recommend a converter as you already have ctx

slate swan
#

u are better off using slash commands and modals lmao

sick birch
pliant gulch
mental quiver
#

how can I stop this function ?

pliant gulch
#

Also if you ever typehint make sure you actually have a type checker installed

#

Otherwise you'l hate your past self

cerulean folio
slate swan
#

or stop as stop allows the function to finish

pliant gulch
#

Vscode if you install the "python" extension it comes bundled with pyright

#

So you should already have a type checker

mental quiver
pliant gulch
#

You could probably test via py foo = "bar" reveal_type(foo) should say foo is of type str in your IDE

slate swan
mental quiver
pliant gulch
# cerulean folio oh alright !

Also I recommend for your check spacing out the expressions instead of having one huge expression block it makes it harder to read for some people

cerulean folio
pliant gulch
#

Yesno

#

It's now list - list but that doesn't do what you want

cerulean folio
sick birch
pliant gulch
#

What are you trying to do?

#

Check if there is any mentions?

cerulean folio
#

It's a filter

sick birch
#

That filters what?

pliant gulch
#

message.mentions -> list so if empty means there is no mentions

cerulean folio
#

Well I want the bot to wait for a message that container either NOTHING more than mentions, or a valid id

pliant gulch
#

if you just wanna check if there is no mentions do like if not message.mentions

cerulean folio
#

and that's the function that will just return if this condition has been satisfied or not

#

so i can pass it to await bot.wait_for()

hushed galleon
#

@cerulean folio as a related pointer, i think you can ask more about general style/refactoring in the channel #software-architecture

cerulean folio
pliant gulch
#

Also is there a reason your only doing this via wait_for? You cannot refactor this into a message command or something?

slate swan
#

yea i already suggested using commands with a modal

pliant gulch
#

if not message.mentions and message.content.isdigit()

#

So, if there is no mentions and the message is only containing digits

cerulean folio
#

For example
hello @dude how are you wouldn't be captured
@dude would be captures
I have 27 years old wouldn't be captured
13554 wouldn't be capture unless it's a valid discord id :D

pliant gulch
#

Yea, just add a couple of ands

cerulean folio
sick birch
hushed galleon
#

discord-specific stuff would be fine here since you'll get people that know about the API/library you're using

pliant gulch
#

MemberConverter might be overkill if you use mentions, but I'd def use it for IDs as there could be multiple ways to search

cerulean folio
#

Ok so here's the thing, the bot needs to ask Who is the member? and will wait for a correct answer which is either a valid ID or a mention. But I want the user to be able to speak freely without the bot stopping on anything they say if that makes sense so when the bot asks for the member, you could chat until you either write @dude or 135438451335654 for eg

I'm sorry for poor explainations

pliant gulch
#

Well you were on the right track but one of your expressions wouldn't have worked

#

That being checking if the content only has a mention

cerulean folio
#

message.content.split(' ') - message.mentions
I thought this would return True if there's something remaining from deleting message.mentions from message.content.split(' ') and False if not? So I just need to actually invert it, so I need not (message.content.split(' ') - message.mentions). Am I wrong?

pliant gulch
#

Also it might not exactly be <@user_id> I forgot whether or not discord sends GW messages as the raw or changed version

#

So you should test with a message and print out the content first

cerulean folio
pliant gulch
#

You should also first check if message.mentions even has a mention e.g len is not 0 or use if to check if truthy

lilac hatch
#

TLDR: I'm looking for an opportunity to assist someone in developing their discord bot project/idea and wanting to get my feet wet again.

Hey everyone, just had a job interview go horribly bad with multiple technical interviews about doing some work in python with other things. Even though I have past experience with Python in a previous job doing some scripting and testing, I haven't practiced the language in a while (not really sure what I was thinking when I applied), and those interviews humbled me real quick. Overall I have past experience as a dev but it was more along the lines of infrastructure and not as much on the application side.

Would there be anyone kind enough to let me pitch in as a contributor for their discord project? Am willing to add to wherever areas I can and want to be a long term contributor alongside someone or a team with their project.

Also, don't know if this is the right place to ask this, but figured I'd start somewhere.

cerulean folio
#

btw @pliant gulch I can code a tiny regex checker for not (message.content.split(' ') - message.mentions) wouldn't it be a good idea? like I try to isoate anything that isn't <@bunch of numbers> and see if the result is of length 0?

sick birch
# lilac hatch TLDR: I'm looking for an opportunity to assist someone in developing their disco...

Hello! We're glad to have you with us. I can see where you're coming from, and why you want to improve your skills. I think the best bet for you currently, while also taking into account your interests, is to contribute to open source software. That doesn't have to be Discord bots, of course, but it seems to be what you're interested in. If you run !src, you can get a link to @unkempt canyon's codebase on GitHub where we accept code changes to add new features, patch existing bugs, etc. @lament depot is more oriented towards people just getting their feet wet (such as yourself). The codebase is significantly easier to work with as well. You will find the repository under the Python Discord GitHub organization. The "to-do" items can be found under "issues", where after discussion, you can ask to take up a certain issue. It will be assigned to you and you can then work on it. If you've got any questions, feel free to pop over to #dev-contrib and ask us there. The channel is meant for contributors or potential contributors such as yourself.

On another note, if you want to improve your Python skill all around to become more well-rounded in regards to Python as a whole, !resources has a bunch of resources on all the different fields under the sun that you can learn about. Then, you can use the !projects command to get a list of projects that you can attempt to do yourself. As a community, we're here as a support structure, so if you ever need help with any of that, you can feel free to ask about that and we'd be willing to help!

pliant gulch
#

And doing it that way instead of regex also means you wonโ€™t need to check how many matches, youโ€™d only need that

severe rampart
#

thing is, python is already as slow as molasses as a programming language, so what's wrong with the code being a little slower?

lilac hatch
pliant gulch
#

I donโ€™t understand why people say, oh yea python is slow so whatโ€™s the harm?

severe rampart
#

if you want the code to be fast you should just... use C++ or something-

sick birch
pliant gulch
#

Regardless of language you wanna be efficient

sick birch
#

Not a lot of merit behind it, when you consider other factors than solely cherry picking runtime speed

severe rampart
#

true ยฏ_(ใƒ„)_/ยฏ

pliant gulch
#

Even C++ can be slow if you write like O(n^6) algo or something

severe rampart
#

that would be painful to watch

sick birch
#

But generally speaking, as Luna said, I wouldn't worry about speed too much in Python

#

Not the primary goal of the language, it's not built with speed in mind either

#

Use whichever option you're more comfortable with, or whichever is more readable

pliant gulch
#

Comparing C++ to python is kind of like comparing apples to oranges imo

severe rampart
#

3.11 is a bit faster than the previous versions of python, but either way it's still going to be pretty slow, try not to focus on speed unless it's causing a huge detrement to the program

pliant gulch
#

The two languages completely cater towards different things

#

I also think Cpython is removing the GIL for some other alternative which will hopefully boost the speed

#

But in the current context do you really want to, Regex search, Len check then do whatever, or just check == of the string then do something?

severe rampart
#

could you define GIL real quick? sorry. lol.

#

not used to many acronyms

pliant gulch
#

The global interpreter lock

#

Itโ€™s why python is so slow

#

That and itโ€™s interpreted

severe rampart
#

compiled will almost always be faster than interpreted, i think

pliant gulch
#

Probably but also I think it depends on the source

#

Also the optimisations

#

Like if you didnโ€™t optimise your LLVM ir or something

lilac hatch
#

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

slate swan
#

im confused. why not just call the function inside the command?

#

lol so ur using someone else's code and dk what ur doing. u should probably mention that. google how to call python functions

#

calling a function is basic python and you somehow know how to use an API to create a payment link yet can't call the function itself

primal token
slate swan
primal token
#

How so?

slate swan
#

well one he deleted all his messages

#

and two he was just copying code

primal token
#

I wouldn't question someones curiosity due to past behavior or/and experiences

slate swan
#

huh?

primal token
#

Atleast give good info to everyone no matter if the user shows interest or not

slate swan
#

i mean the link i sent shows and describes the proper way to def and call a function. yet he "already" knew how to create a function just didn't know how to call it.

primal token
#

Ok and that has what to do what with my point?

#

With all due respect I'm not sure what your point was, can you re word it?

slate swan
#

you just said give good info no matter if the user shows interest or not lmao. i just explained to you that what i referred him to was good info pertaining to his "issue"

primal token
#

Not really? You gave him a site about functions that also shows the calling of them, yes, while what i gave has an in depth talk about the calling of functions specifically? https://realpython.com/lessons/function-calls-definitions/

Now letโ€™s take a look at function calls and definitions. To call a functionโ€”to use a function, or invoke, are other terms that we useโ€” you simply give the name of the function and then, followed in parentheses, argument valuesโ€”if anyโ€”that areโ€ฆ

slate swan
#

Python HTTP Server/Client: Remote end closed connection without response error hello who got fix for this ?

obtuse blaze
#

so I have this daily command that you can use every 24h, problem is the follow:
If I restart bot to make update everyone gets a free daily since timer resets... how can I fix this?

slate swan
#

you can't

#

unless you make some custom cooldown and store when they use it in a db

obtuse blaze
#

tyty

silk fulcrum
#

Provide at least full traceback

slate swan
#
@bot.slash_command(name="reroll")
async def reroll(interaction: nextcord.Interaction, channel: nextcord.TextChannel, id_ : int = nextcord.SlashOption(name="message_id", description="The giveaway message id!")):

    new_message = await channel.fetch_message(id_)
    
    users = await new_message.reactions[0].users().flatten()
    users.pop(users.index(bot.user))
    winner = random.choice(users)

    reroll_announcement = nextcord.Embed(color = 0xff2424)
    reroll_announcement.set_author(name = f'The giveaway was rerolled by: {interaction.user.mention}', icon_url = 'https://media.discordapp.net/attachments/1007641111776481371/1008627898846027836/noadgifdev.gif')
    reroll_announcement.add_field(name = f'New Winner:', value = f'{winner.mention}', inline = False)
    await channel.send(embed = reroll_announcement)
slate swan
#

oh nextcord uhhh

slate swan
#

lemme@check

slate swan
#

okay thank you!

silk fulcrum
#

oh that's an Option

slate swan
slate swan
silk fulcrum
#

I thought that was a regular argument

slate swan
#

yea aint too much extra work tho. it's cause the size of the ints too large

#

yeee the inside the function just make sure u convert it to a int

slate swan
#

wait how

#

idk tbh loll

#

lmaoo hmm

#

BUT if its working lets just keep it that way hahha

#

hope it wont hit me

south coyote
#

i got that bot to send the notification to the webhook

#

totally brain fart

obtuse blaze
#
@remind_handler.before_loop
    async def before_remind_handler(self):
        await self.bot.wait_until_ready()```
AttributeError: module 'discord.ext.commands.bot' has no attribute 'wait_until_ready'
here's the code
this appears after i stop the bot
slate swan
little lava
#

Do i must use (interaction) function parameter instead of (ctx) in discord 2.0 ?

naive briar
#

Interactions are used in app commands, but if you're using text commands, you can still use ctx

vital glacier
#

anyone that's got good knowledge of how error handlers work and whats possible with them? i need help in private to make my error handler like i want but i have no idea how to get any further

vital glacier
#

no

slate swan
#

Oh

vital glacier
#

like global error handlers used for every error it can give

slate swan
#

OH

#

idk how to do it too

#

letme check

vital glacier
#

I'm basically trying to make it so every error gets the same embed with the same layout, but for every error/missing argument or something it just creates the message its supposed to and then send the message

naive briar
#

!d discord.Client.on_error

unkempt canyonBOT
#

await on_error(event_method, /, *args, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

The default error handler provided by the client.

By default this logs to the library logger however it could be overridden to have a different implementation. Check [`on_error()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_error "discord.on_error") for more details.

Changed in version 2.0: `event_method` parameter is now positional-only and instead of writing to `sys.stderr` it logs instead.
vital glacier
#

Let's read it through

little lava
slate swan
#

it is better practice to yes so you don't confuse the two

slate swan
slate swan
#

Ctx

#

ctx.author.id

#

Oh

#

Ty

silk fulcrum
# little lava

You could also use typehinting:

@tree.command()
async def help(i: discord.Interaction):```
slate swan
#

way better btw

south coyote
#

how do you say user = discord.get.utils = (interaction.user)

slate swan
#

nice variable naming

silk fulcrum
#

Btw, I don't see a need in a help command for slash commands, but whatever

silk fulcrum
south coyote
#

how do you define the user that clicked the slash command is what i mean

slate swan
silk fulcrum
#

for i: discord.Interaction in range(8):

#

.utils()?

slate swan
unkempt canyonBOT
slate swan
#

there's no role of utils in there

south coyote
#

thx

silk fulcrum
#

yayyyy, I finally found something that seems to work with this stupid lib

slate swan
#

yeah i hate this lib

vital glacier
#

anyone got any idea how the MissingRequiredArguments error works?

#

actually nvm

south coyote
#

is there a way to return the number of messages that a user has sent?

#

like i want to greet people when they send their first message

slate swan
#

in a channel, yes
in the server also yes, but its a bit complex

#

!d discord.TextChannel.history

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the destinationโ€™s message history.

You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") to do this.

Examples

Usage...
sharp sky
#

Hey

slate swan
#

check for messages that were from the user

#

set limit to None

lofty lance
#

hey i am getting some issues in my discord bot

#

can anyone help pls

south coyote
#

like dis?

async for message in channel.history(limit=None):
    if message = 0:
        await (f"Hello {interaction.user}")
south coyote
#

anybody

lofty lance
#

can u help me pls

south coyote
#

what sup

#

ill try

lofty lance
#

i am getting some issue while running simple command

south coyote
#

post the code

lofty lance
#

when i run it it shows none
but its suppose to show me data from .env file

#

thats my token

south coyote
#

is it because you spellled secret wrong?

lofty lance
#

is it

#

but it doesnt matter coz that a var name

south coyote
#

oh ok

lofty lance
#

its not english

south coyote
#

hmm

#
from python_settings import settings
from . import settings as my_local_settings

settings.configure(my_local_settings) # configure() receives a python module
assert settings.configured # now you are set
naive briar
naive briar
#

!d os.getenv

unkempt canyonBOT
#

os.getenv(key, default=None)```
Return the value of the environment variable *key* as a string if it exists, or *default* if it doesnโ€™t. *key* is a string. Note that since [`getenv()`](https://docs.python.org/3/library/os.html#os.getenv "os.getenv") uses [`os.environ`](https://docs.python.org/3/library/os.html#os.environ "os.environ"), the mapping of [`getenv()`](https://docs.python.org/3/library/os.html#os.getenv "os.getenv") is similarly also captured on import, and the function may not reflect future environment changes.

On Unix, keys and values are decoded with [`sys.getfilesystemencoding()`](https://docs.python.org/3/library/sys.html#sys.getfilesystemencoding "sys.getfilesystemencoding") and `'surrogateescape'` error handler. Use [`os.getenvb()`](https://docs.python.org/3/library/os.html#os.getenvb "os.getenvb") if you would like to use a different encoding.

[Availability](https://docs.python.org/3/library/intro.html#availability): Unix, Windows.
south coyote
#

you're importing it wrong

slate swan
#

no he isn't

south coyote
#
from python_settings import settings
from . import settings as my_local_settings

settings.configure(my_local_settings) # configure() receives a python module
assert settings.configured # now you are set
slate swan
#

he is importing fine

#

To check if more than 24 hours and less than 48 hours passed since you successfully called a certain command, is there a special way for that?

slate swan
# lofty lance yup

how are u storing the variable? like
TOKEN= "asdfasdfgh"
or
TOKEN = asldfhasdf

#

Or should I just do it with datetime?

slate swan
#

remove the quotes

#

should be storing like this
TOKEN = aslhdfajsdf

shrewd apex
#

it dosent matter

slate swan
#

And any articles on that?

slate swan
shrewd apex
#

its coz the env is not being loaded by load_dotenv

#

or he entred wrong key value

lofty lance
slate swan
slate swan
#

i do the exact format as you.

lofty lance
#

nope not working in my case

slate swan
#

and ur sure nothing is misspelled?

#

show ur env file without exposing ur token

shrewd apex
#
# settings.py
import os
from dotenv import load_dotenv

def get_token() -> None | str:
    load_dotenv('.env')
    return os.getenv('TOKEN') #MAKE SURE SPELLING IS RIGHT
# main.py
from settings import get_token
print(get_token())
slate swan
#

ur doing the exact same thing he is doing but adding extra steps

shrewd apex
#

i don't even see the point of having a settings.py for token

slate swan
#

most ppl use a similar system to store variables

south coyote
#

welcomerole = discord.utils.get(guild.roles, name="978169169013002240")

what do you think

#

nm

#

im not sure what the guild.roles does

shrewd apex
#

who names their role same as role id pithink

south coyote
#

no its the role_id

#

why is guild getting a squiggyly line under it

slate swan
#

yea so use id= not name=

south coyote
#

still

#
@bot.event
async def on_member_join(member, interaction: discord.Interaction):

  if member.guild.id !=935395948727779328:    
    return 
  welcomerole = discord.utils.get(guild.roles, id=978169169013002240)
  await member.add_roles(welcomerole)
  channel = bot.get_channel(1034633261516853390)
  await channel.send(f"Welcome {interaction.user}") 
slate swan
#

that doesn't work u made ur role id a string

#

remove the quotes

south coyote
#

oh my bad

slate swan
#

also member_join doesn't take interaction.

#

welcome{member.mention}

south coyote
#

ahhh

topaz helm
#

@topaz helm

south coyote
#

thanks haymart

#

jaymart

south coyote
#

drink some water everybody

alpine cove
timid pawn
#

hello guys

#

i'm working with a scheduled event object for a discord_bot, all the attributes provided for scheduled_events does not contain a time_posted. I can use a datetime.now() when i get the event with on_scheduled_event_create event but its not so clean, is there any cleaner way to have this done

slate swan
timid pawn
slate swan
#

yeah there is no other time attributes other than end_time

timid pawn
#

and not when the event was published

slate swan
#

that doesn't exist

timid pawn
slate swan
#

yup

timid pawn
#

okay, thanks

slate swan
#

Guys

#

How do i make an invites command like its taking on_member_join but idk hiw do i act do it and didnt find a tutorial

#

im sure github has code, there is no easy way to do it

#

oh

#

thanks

#

actually i think someone made a dpy extension specifically for that

#

Here?

#

nvm that is outdated as shit

#

it was disnake i was thinking of . but just search github for discord py invite tracker you'll find alot of examples

#

Oh thanks

placid skiff
#

neither disnake has something to handle invites lmao

slate swan
#

yes it does i literally use it

placid skiff
#

in the API there is nothing that let you track the invites

slate swan
#

bro i said an extension

#

not the main lib

placid skiff
#

yeah but i think that you are confusing things lmao
disnake has an Invite object but it doesn't handle people who join through that invite

slate swan
#

bro what no i am not someone made a seperate lib, an extension using the disnake lib to track invites

placid skiff
#

lmao ok

slate swan
#
from disnake.ext.invitetracker import InviteLogger
from lib.db import db
from lib.bot import bot

invite = InviteLogger(bot)


class Invites(Cog):
    def __init__(self, bot):
        self.bot = bot

    @Cog.listener()
    async def on_member_join(self, member: disnake.Member):
        db.execute("INSERT OR IGNORE INTO members (userid) VALUES (?)", member.id)
        db.commit()

        data: disnake.Invite = await invite.get_invite(member)

        db.execute("UPDATE members SET invites = invites + ? WHERE userid = ?", 1, data.inviter.id)
        db.commit()

like i said I quite literally use it dude

placid skiff
#

btw it is easy in the end
Just check between all active invites which one uses count increase lmao

south coyote
#

does this look right?

#
@discord.ui.button(label= "Click me!", style=discord.Buttonstyle.blurple, emoji=":wave:")
async def click_me(button: discord.ui.Button, interaction: discord.Interaction):
    await interaction.response.send_message("You clicked me!")
#

no i need a tree command that brings up the view huh?

#

i hope im on the right track

#

i can't understand docs so i have to piece together what other people are doing in videos

#

and the help i get in here

eager portal
#

what is better? next cord or discord py v2

slate swan
#

dpy v2

south coyote
#

hey sarth what do you think about htiis

#

class MyBot(discord.Client):
    def __init__(self) -> None:
        super().__init__(intents=discord.Intents.all())
        self.synced = False 

    async def on_ready():
        print("Logged in")
        try:
            synced = await bot.tree.sync()
            print(f"Synced {len(synced)} commands")
        except Exception as e:
            print(e)

bot = MyBot()

#

purty huh

slate swan
#

use setup_hook to sync

#

and there's nothing like discord.bot

south coyote
#

setup_hook?

#

await setup_hook?

unkempt canyonBOT
#

examples/app_commands/basic.py lines 25 to 29

async def setup_hook(self):
    # This copies the global commands over to your guild.
    self.tree.copy_global_to(guild=MY_GUILD)
    await self.tree.sync(guild=MY_GUILD)```
south coyote
#

omg

#

god bless you

#

so llike this then

#

this says MyBot() has no attribute 'tree'

import discord
from discord.ext import commands


class MyBot(discord.Client):
    def __init__(self) -> None:
        super().__init__(intents=discord.Intents.all())

    async def on_ready():
        print("Logged in")
        try:
            synced = await bot.tree.sync()
            print(f"Synced {len(synced)} commands")
        except Exception as e:
            print(e)

bot = MyBot()

@bot.tree.command(name = "hello")
async def hello(interaction: discord.Interaction):
#    user = discord.Interaction.user
    await interaction.response.send_message(f"Hello!")
unkempt canyonBOT
#

examples/app_commands/basic.py lines 13 to 20

# A CommandTree is a special type that holds all the application command
# state required to make it work. This is a separate class because it
# allows all the extra state to be opt-in.
# Whenever you want to work with application commands, your tree is used
# to store and work with them.
# Note: When using commands.Bot instead of discord.Client, the bot will
# maintain its own tree instead.
self.tree = app_commands.CommandTree(self)```
naive briar
#

Someone already sent you an example

#

What's the problems

slate swan
#

can it work with a message

#

and to w an embed?

naive briar
#

What are you trying to do

south coyote
#

im getting this error

File "/home/deusopus/Desktop/mr_bud.py", line 14, in setup_hook
    self.tree.copy_global_to(guild=MY_GUILD)
AttributeError: 'MyBot' object has no attribute 'tree'
#

so i need to give it an attribute of tree

#

where do attributes live?

naive briar
south coyote
#

my bad

#
Traceback (most recent call last):
  File "/home/deusopus/Desktop/mr_bud.py", line 18, in <module>
    self.tree = app_commands.CommandTree(self)
NameError: name 'self' is not defined
#

yes help you i may

naive briar
#

Where did you put that

south coyote
#
class MyBot(discord.Client):
    def __init__(self) -> None:
        super().__init__(intents=discord.Intents.all())

    async def on_ready(self):
        print("Logged on as {0}!".format(self.user))
 
    async def setup_hook(self):
        self.tree.copy_global_to(guild=MY_GUILD)
        await self.tree.sync(guild=MY_GUILD)

client = MyBot()
self.tree = app_commands.CommandTree(self)
naive briar
#

Don't just copy and paste

south coyote
#

i dont

unkempt canyonBOT
#

examples/app_commands/basic.py lines 13 to 20

# A CommandTree is a special type that holds all the application command
# state required to make it work. This is a separate class because it
# allows all the extra state to be opt-in.
# Whenever you want to work with application commands, your tree is used
# to store and work with them.
# Note: When using commands.Bot instead of discord.Client, the bot will
# maintain its own tree instead.
self.tree = app_commands.CommandTree(self)```
south coyote
#

i kinda do

naive briar
#

Go into that link

shrewd apex
south coyote
#
import discord
from discord import app_commands

MY_GUILD = discord.Object(id=935395948727779328)

class MyBot(discord.Client):
    def __init__(self, *, intents: discord.Intents):
        super().__init__(intents=intents)
        self.tree = app_commands.CommandTree(self)
 
    async def setup_hook(self):
        self.tree.copy_global_to(guild=MY_GUILD)
        await self.tree.sync(guild=MY_GUILD)

intents = discord.Intents.default()
client = MyBot(intents=intents)

@client.event
async def on_ready():
    print(f'Logged in as {client.user} (ID: {client.user.id})')
    print('------')

@client.tree.command(name = "hello", description="greeting")
async def hello(interaction: discord.Interaction):
    await interaction.response.send_message(f"Hello!")

@client.tree.command(name = "lets-goooooo", description="the battle cry")
async def letsgo(interaction: discord.Interaction):
    await interaction.response.send_message(f"Let's goooooo!")

@client.tree.command(name = "to-the-mooon", description="the motto")
async def tothemoon(interaction: discord.Interaction):
    await interaction.response.send_message(f"To the moooon!")

@client.tree.command(name = "button", description="generic button")
async def button(interaction: discord.Interaction):
    await interaction.response.send_message(f"button button button")
#

there we go that link was very helpful

#

thank you so much

south coyote
#

now im working on making buttons

toxic turtle
#

Hi all Im having a problem, I want the bot to send a message at a certain time of the day but it doesnt work I'm not even sure if the code is correct, any one can help me plz

#

when I run it also without any errors O.o

slate swan
toxic turtle
#

ok thank a lot, I will try

south coyote
#

okay so where is a good example of buttons using that template i posted

toxic turtle
#

still doesnt work, am I missing something?๐Ÿฅฒ

south coyote
#

i cant believe my memory

#

how do you mention a member or user without defining member or user

#
await interaction.response.send_message(f"Hello! Welcome {member.mention}")
#

is not working

#

nm

feral frost
#

guys help pls. My imports are not working

placid skiff
#

are you using pycharm? even if not check if you're using a venv

south coyote
#

hmmm

#

i would like to make a button that people can click

#

i wonder if there is a good tutorial that fits into what i have learned already

little lava
slate swan
south coyote
zealous jay
#

How do I use a select menu inside a cog?

slate swan
#

you use it

trim ocean
#

How do you get the first reactions from a message?

naive briar
#

!d discord.Message.reactions

unkempt canyonBOT
zealous jay
south coyote
#

so how about if you want to say if member has role then do something else.....

#

if member.role is

#

if member.role not

#

if user.role not

#

i don't now

#

if type(client.role)?

#

role = discord.utils.get(message.server.roles, name=entered_team)

upbeat otter
# south coyote so how about if you want to say if member has role then do something else.....

basically, you'll need a member object first and then access the member's roles using the roles property and check if the member has the role or not

member: discord.Member

''' searching using a Role object '''

guild = bot.get_guild(guild_id)
role = guild.get_role(role_id)

if role in member.roles:
  # do something

 # -------------------------------------

''' searhing by name '''
role_names = [role.name for role in member.roles]
if 'rolename' in role_names:
  # do something

 # -------------------------------------

''' searching by an id '''
role_ids = [role.id for role in member.roles]
if 12345654321 in role_ids: #random characters is the role id here
  # do something

south coyote
#

god bless you

upbeat otter
#

๐Ÿ› you're the god, bless me

south coyote
#

blesseth be

upbeat otter
#

๐Ÿ›

naive briar
#

!d discord.Member.get_role

unkempt canyonBOT
#

get_role(role_id, /)```
Returns a role with the given ID from roles which the member has.

New in version 2.0.
upbeat otter
#

was gonna do that too

#

๐Ÿ˜”

naive briar
#

๐Ÿคท

#

Wait

#

Was that a new emoji

upbeat otter
#

idk

#

apparenty

vale wing
#

The best new emoji is ๐Ÿซฆ

upbeat otter
#

tf is this ๐Ÿ’€

vale wing
#

Cause you can do this

#

๐Ÿซฆ๐Ÿฆถ

upbeat otter
#

๐Ÿ’€

#

my humour level is too out of league for the people here ngl

#

๐Ÿ’€ like anything wtf

topaz helm
#

can someone help me?

naive briar
#

Delete one space in front of else statement

south coyote
#

so kinda like this.... if guild.get_role(mod_role) is None:?

naive briar
#

Make sure they're in the same indent level

lucid latch
#
async def play(ctx: interactions.CommandContext, query: str):
    queue = []
    if not discord.VoiceClient[0].is_connected():
        await discord.VoiceClient[0].connect()```
#

TypeError: 'type' object is not subscriptable

#

what's the matter?

south coyote
#

if interaction.guild.get_role(mod_role) is None:

#

i think that is it

topaz helm
naive briar
topaz helm
south coyote
#
if interaction.guild.get_role(mod_role) is None:
        await interaction.user.add_roles(mod_role)
        await interaction.response.send_message(f"I have given you {client.role.mention}!", ephemeral = True)
    else:
        if interaction.guild.get_role(mod_role) is not None:
            await interaction.response.send_message(f"You don't need {client.role.mention}!", ephemeral = True)
#

i think that works

#

logiccally

primal token
#

It really doesn't make sense

south coyote
#

well it works except for the client.role.mention

#

how do you mention the role that was just given

#

or i could just cut out the middleman and say you got it or you didn't

#

just flat out

primal token
#

Because it works doesn't mean its logic can be optimized or changed

south coyote
#
class button_view(discord.ui.View):
    def __init__(self) -> None:
        super().__init__(timeout=None)
    
    @discord.ui.button(label = "Get Moderator Role, Now!", style = discord.ButtonStyle.green, custom_id = "role_button")
    async def get_mod(self, interaction: discord.Interaction, button: discord.ui.Button):
        if interaction.guild.get_role(mod_role) is None:
            await interaction.user.add_roles(mod_role)
            await interaction.response.send_message(f"I have given you {client.role.mention}!", ephemeral = True)
        else:
            if interaction.guild.get_role(mod_role) is not None:
                await interaction.response.send_message(f"You don't need {client.role.mention}!", ephemeral = True)

@client.tree.command(guild=MY_GUILD, name = 'get-mod-perms', description='Get moderator permissions!')
async def launch_button(interaction: discord.Interaction): 
    await interaction.response.send_message(view = button_view())
#

it's that {client.role.mention} that needs fixed

primal token
south coyote
#

im sorry?

#

im not familiar with that term

primal token
#

!d EAFP

unkempt canyonBOT
#

Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.

primal token
#

!d LBYL

unkempt canyonBOT
#

Look before you leap. This coding style explicitly tests for pre-conditions before making calls or lookups. This style contrasts with the EAFP approach and is characterized by the presence of many if statements.

In a multi-threaded environment, the LBYL approach can risk introducing a race condition between โ€œthe lookingโ€ and โ€œthe leapingโ€. For example, the code, if key in mapping: return mapping[key] can fail if another thread removes key from mapping after the test, but before the lookup. This issue can be solved with locks or by using the EAFP approach.

south coyote
#

that doesn't apply necessarily

#

as you can see i have an if statement that looks for their existing role

#

if the moderator role is non existent ie None then it grants them the moderator role

#

if interaction.guild.get_role(mod_role) is None:

await interaction.user.add_roles(mod_role)

#

if they don't have mod role give them mod role

#

then

#

if interaction.guild.get_role(mod_role) is not None:

#

await interaction.response.send_message(f"You don't need {client.role.mention}!", ephemeral = True)

slate swan
south coyote
#

pretty colors

slate swan
slate swan
#

even if im ending the giveaway

#

its not rlly ending it

south coyote
#

you won

#

congrats!

slate swan
#

no but it was after it

south coyote
#

you totally scrolled my convo though bro

naive briar
primal token
slate swan
south coyote
#

as i was saying

slate swan
#

just sending that it ended but it didnt rlly

south coyote
#

please scroll back

#

i could just flat out say they got the mod role or they don't need the mod role either way

#

i don't need to pull the role

primal token
#

The thing is your logic in your code doesnt make sense, you're checking if the role is in cache not in the author๐Ÿค”

south coyote
#

how do i check the author

primal token
#

You can use EAFP or LBYL

south coyote
#

if interaction.author.get_role(mod_role) is None:

#

like that

primal token
#

Yes

south coyote
#

im pretty sure those techniques aren't necessary here

#

but thanks for future ref

primal token
#

How so?

south coyote
#

i know what you are saying but it's too simple

primal token
#

And the problem being?

south coyote
#

user.roles

#

how to mention the role that was just given in a message

#

await interaction.response.send_message(f"You don't need {client.role.mention}!", ephemeral = True)

#

like how do i make that say "You don't need the moderator role"

#

with formatting of the call to roles

slate swan
south coyote
#

or the search of roles i guess you would say

#

user.roles?

primal token
topaz helm
#

does anyone know why it doesn't work? it's correct? when I try to test, nothing happens

south coyote
#

{interaction.user.role.mention}

#

because you have to instantiate itself as an object

topaz helm
slate swan
#

oh okay

south coyote
#

me, you, them

vale wing
south coyote
#

Lesbian Basketball Youth League

topaz helm
#

@slate swan how can I make it work?

south coyote
#

with a little help from your friends

slate swan
south coyote
#

i can only send parts of the code

#

tiny little bits at a time

topaz helm
slate swan
#

ofc

south coyote
#

i like my code hot off the grill

cloud dawn
#

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

vale wing
#

When I get home imma sudo do-release-upgrade

topaz helm
#
@commands.command()
@commands.has_permissions(manage_messages=True)
async def warn(self, ctx, member: discord.Member, * , reason = None):
  
    em = discord.embed(title = "Member Warned!" , description = f'{member} was been warned for: {reason}', colour = discord.Colour.random())

    await ctx.send(embed = em)

  
@commands.command()
@commands.has_permissions(manage_messages=True)
async def unwarn(self, ctx, member: discord.Member):
  
    em = discord.embed(title = "Member Warned!" , description = f'{member} was been warned', colour = discord.Colour.random())

    await ctx.send(embed = em)
south coyote
#

let's code some python girls and guys

vale wing
south coyote
#

i hate the fact that it is called python

#

i hate that name

topaz helm
slate swan
#

also in unwarn

vale wing
#

Ah yes finally

primal token
#

fyi Python wasnt named after the snake lol

topaz helm
topaz helm
#

there are no errors in the console

slate swan
#

so when i do the end command its not really ending, yes its sending a winner but it should look like that when i end that

slate swan
topaz helm
#

I don't really know what you mean

slate swan
primal token
#

His issues arent due to imports or attributes it seems like he's using commands.command to register commands when he's not inside a cog, from the look of indentation

topaz helm
vale wing
#

๐Ÿง

topaz helm
#

also for warn/unwarn

primal token
slate swan
topaz helm
#

ok

primal token
#

and remove self

slate swan
vale wing
#

This is the story of how a man outside of cog thought he is inside

topaz helm
#

now there are errors

slate swan
vale wing
#

๐Ÿค—

slate swan
#

can u send the whole pic of ur code(just not the token)

primal token
#

client variable naming lol

topaz helm
slate swan
#

!share

#

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

south coyote
#

something like Mrs. Python or something

south coyote
#

i know i was just playing

primal token
south coyote
#

did you throw up?

primal token
#

Ok

south coyote
#

I don't like SPAM

#

Now for something completely different

#

Bicycle Repairman

#

that's a good one

alpine cove
south coyote
#

No i think it was sarcasm

#

Life of Brian

#

all that rot

#

Terry Gilliam

alpine cove
unkempt canyonBOT
#

@alpine cove :white_check_mark: Your 3.11 eval job has completed with return code 0.

1
slate swan
#

so when i do the end command its not really ending, yes its sending a winner but it should look like that when i end that

tulip oracle
#

possibly a stupid question but looping through every message since the start of the month in my server to check how many times a keyword was said by each user?

south coyote
#

can do

#

i think

tulip oracle
#

possibility of being banned?

south coyote
#

i did what i was trying to do

#

await interaction.response.send_message(f"I have given you {interaction.user.get_role(979353319644479559)}!", ephemeral = True)

feral frost
#

how can i make a form tab like this ?

alpine cove
feral frost
#

?

feral frost
drowsy prairie
#
    smart_Switch_Off = Button(label = "OFF", style = discord.ButtonStyle.red)

            # discord channel switch on button
    async def smart_switch_on_callback(interaction):
        await interaction.response.defer()
        await msg.edit(embed=switch_On_Embed)
        print(f"{msg.author.name}")

            # discord channel switch off button
    async def smart_switch_off_callback(interaction):
        await interaction.response.defer()
        await msg.edit(embed=switch_Off_Embed)

            # button callback
    smart_Switch_On.callback = smart_switch_on_callback
    smart_Switch_Off.callback = smart_switch_off_callback

    view = View(timeout=None)

    view.add_item(smart_Switch_On)
    view.add_item(smart_Switch_Off)

How do I know the name of the user who clicked the button?

naive briar
#

!d discord.Interaction.user

unkempt canyonBOT
naive briar
unkempt canyonBOT
slate swan
south coyote
#

i wish i could figure out how to give someone a role when they press a button

#

i got this so far

south coyote
#

thanks buddy

#
@discord.ui.button(label = "Get OG Status, Now!", style = discord.ButtonStyle.green, custom_id = "role_button")
    async def get_mod(self, interaction: discord.Interaction, button: discord.ui.Button):
        if interaction.user.get_role(985708739392839720) is None:
            await interaction.user.add_roles(interaction.user.role(985708739392839720), reason=reason )
            await interaction.response.send_message(f"I have given you {interaction.user.get_role(985708739392839720)}!", ephemeral = True)
        else:
            if interaction.user.get_role(985708739392839720) is not None:
                await interaction.response.send_message(f"You don't need {interaction.user.get_role(985708739392839720)}!", ephemeral = True)
#

i just need the line about adding the role to the person that clicked the button everything else works

slate swan
#

first of everything

#

u need a class for that and to create a command for the button

south coyote
#

oh yeah i do

slate swan
#

send it all

south coyote
#
class button_view(discord.ui.View):
    def __init__(self) -> None:
        super().__init__(timeout=None)
    
    @discord.ui.button(label = "Get OG Status, Now!", style = discord.ButtonStyle.green, custom_id = "role_button")
    async def get_mod(self, interaction: discord.Interaction, button: discord.ui.Button):
        if interaction.user.get_role(985708739392839720) is None:
            await interaction.user.add_roles(the struggle is real)
            await interaction.response.send_message(f"I have given you {interaction.user.get_role(985708739392839720)}!", ephemeral = True)
        else:
            if interaction.user.get_role(985708739392839720) is not None:
                await interaction.response.send_message(f"You don't need {interaction.user.get_role(985708739392839720)}!", ephemeral = True)

@client.tree.command(guild=MY_GUILD, name = 'get-og-status', description='Get OG status!') #guild specific slash command
async def launch_button(interaction: discord.Interaction): 
    await interaction.response.send_message(view = button_view())
slate swan
cloud dawn
#

Any errors?

cloud dawn
#

Why does he need to do that?

slate swan
#

its easier for me tbh

#

@south coyote u need to use discord utils

south coyote
#

yeah

cloud dawn
#

What for?

slate swan
#

discord.utils.get(interaction.guild.roles, name="the name or the id instead of name")

slate swan
cloud dawn
#

His way is fine..?

slate swan
#

ok

sick birch
#

.get_role() is preferred anyway

slate swan
#

await interaction.user.add_roles(Role)

#

like that

cloud dawn
south coyote
#

ive been close

lofty lance
#

hey
i am using args and ctx command to get a message form user
now the message is multi line
and i wana store it same as it is

any idea how can i do it

cloud dawn
#

@south coyote Could you tell us the problem? Right now we're just assuming.

slate swan
lofty lance
south coyote
#

one sec

cloud dawn
slate swan
#

if you mean that all part of the message is not getting consumed you need to add a consume rest argument py async def command(context, *, argument) -> Any: argument will take everything that comes after !command

cloud dawn
# slate swan oh okay thanks!

If you do still want help the current question is kind of vague "look like that when I end that", I don't know what you mean.

#

What should it do when it reaches the end?

south coyote
#
class button_view(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)
        self.value = None
        self.timeout = None
    
    @discord.ui.button(label = "Get OG Status, Now!", style = discord.ButtonStyle.green, custom_id = "role_button")
    async def get_mod(self, interaction: discord.Interaction, button: discord.ui.Button):
        if interaction.user.get_role(985708739392839720) is None:
            role = discord.utils.get(interaction.guild.roles, name="985708739392839720")
            await interaction.user.add_roles(role)
            await interaction.response.send_message(f"I have given you {interaction.user.get_role(985708739392839720)}!", ephemeral = True)
        else:
            if interaction.user.get_role(985708739392839720) is not None:
                await interaction.response.send_message(f"You don't need {interaction.user.get_role(985708739392839720)}!", ephemeral = True)

@client.tree.command(guild=MY_GUILD, name = 'get-og-status', description='Get OG status!') #guild specific slash command
async def launch_button(interaction: discord.Interaction): 
    await interaction.response.send_message(view = button_view())
vale wing
#

Um actually, your's naming convention is sucks ๐Ÿค“

lofty lance