#Basic Pycord Help (Quick Questions Only)

1 messages · Page 49 of 1

full basin
#

Embed won't be affected if you don't supply the kwarg

woeful spindle
#

alr

#

well that’s even simpler

silver moat
#

using ctx.edit ofc

full basin
#

But not quite sure if you can edit a message to remove the file?

silver moat
bold notch
#
    user = ctx.bot.get_user(1059358812051603576)
    embed.set_image(url=user.avatar)
    await ctx.edit(file=None, embed=embed)
bold notch
#

file=None returns the error

silver moat
bold notch
#
Ignoring exception in command summon:
Traceback (most recent call last):
  File "C:\Users\DolyPC\PycharmProjects\DiscordIconsBot\venv\lib\site-packages\discord\commands\core.py", line 124, in wrapped
    ret = await coro(arg)
  File "C:\Users\DolyPC\PycharmProjects\DiscordIconsBot\venv\lib\site-packages\discord\commands\core.py", line 980, in _invoke
    await self.callback(ctx, **kwargs)
  File "C:\Users\DolyPC\PycharmProjects\DiscordIconsBot\main.py", line 88, in summon
    await ctx.edit(file=None, embed=embed)
  File "C:\Users\DolyPC\PycharmProjects\DiscordIconsBot\venv\lib\site-packages\discord\interactions.py", line 415, in edit_original_response
    params = handle_message_parameters(
  File "C:\Users\DolyPC\PycharmProjects\DiscordIconsBot\venv\lib\site-packages\discord\webhook\async_.py", line 672, in handle_message_parameters
    "value": file.fp,
AttributeError: 'NoneType' object has no attribute 'fp'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\DolyPC\PycharmProjects\DiscordIconsBot\venv\lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\DolyPC\PycharmProjects\DiscordIconsBot\venv\lib\site-packages\discord\commands\core.py", line 375, in invoke
    await injected(ctx)
  File "C:\Users\DolyPC\PycharmProjects\DiscordIconsBot\venv\lib\site-packages\discord\commands\core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'fp'

silver moat
#

instead of file=None

proud mason
#

Cool

bold notch
silver moat
woeful spindle
bold notch
limber urchin
#

It's explained in the docs

bold notch
#

I have another question. What determines the order in which users are in ctx.guild.members

flat merlin
#

If I call a modal in a button callback, how would I wait for the modal to be finished? Especially using Modal.wait().

proud mason
#

dont forget to send a response in the modal callback

flat merlin
#

It's in a cog, and using await modal.wait() resulted in this error: TypeError: Modal.wait() missing 1 required positional argument: 'self'

proud mason
#

also are you doing Modal.wait ?
you have to use wait on the modal object, not the class

flat merlin
#

You mean this part?

            def __init__(self3, *args, **kwargs) -> None:
                super().__init__(*args, **kwargs)```
#

I used await start_modal.wait() in the button callback.

proud mason
#

there is a few things wrong with that code blobpain

#

1st- dont name classes in snake case

#

2nd- why self3 blobpain

#

3rd- i have a fear you are naming the object same as the class

proud mason
#

in the button callback

flat merlin
#

I'm unfamiliar with the term snake case. I used self3 because in earlier experiments I tried to access a function through the cog's self, which clashes with the Modal's self if you name them the same.

silver moat
flat merlin
#

Ah, that makes sense.

proud mason
#

I tried to access a function through the cog's self, which clashes with the Modal's self if you name them the same.

wat pepeThink

silver moat
#

everything else in Python should be snake case. Constants however should be SCREAMING_SNAKE_CASE

flat merlin
#

What is the precise definition of constants?

silver moat
#

like MAXIMUM_PLAYER_COUNT which is not going to change throughout the program

proud mason
#

a value which should not change during runtime
python doesnt have a constant
its you as a dev who has to remember to not assign smth to it while coding

flat merlin
bold notch
#

how does pycord change image size in embeds?

silver moat
proud mason
#

you can get bot instance from interaction.client btw

silver moat
#

self3 indicates a button thingy in a modal in a cog.

proud mason
silver moat
#

a lot of unccessary nesting

bold notch
proud mason
bold notch
#

embed.set_image(url=iconuser.avatar, width=256, height=256)

#

height and width are not recognized as arguments

#

i could not find other ways

silver moat
#

.embed

#

.embedsize

#

.embeds

flat merlin
#

I put the class inside a function, because it uses a list that's passed to the function from another function.

bold notch
#

maybe ill try to use a thumbnail instead

proud mason
#

nesting classes gives you fucked up bugs and errors

silver moat
proud mason
flat merlin
#

I admit I barely know what I'm doing with Modal Dialogs and all that stuff, so I'll gladly take any tips that'll make the process easier. 👀

#

I'm trying to see everything that's possible with them for now.

silver moat
#

nesting a subclass is rarely ever done.

flat merlin
#

Then would I place the Modal's class between the imports and the cog's class?

silver moat
#

it should be in the same scope as the cog

proud mason
#

if i understood what you meant correctly

flat merlin
#

Honestly what I said doesn't even make sense to me. 🤔

#

If the class is not inside the function, how will I pass lists to the modal and buttons and back?

silver moat
#

pass it through init

proud mason
#

Then you yourself would understand what to do

flat merlin
#

I'm sorry, I got distracted.

#

I've written out a few lines

north gorge
#

How can a user command take input, can i pop up a modal and handle it that way?

#

and re: that, if so, is there some pre-made facility to do that or do I have to write a modal view/callback for each command

tough briar
#

What's the reason behind that a music 24/7 bot stops playing after a while?

limber urchin
#

That's like asking "why does my car not work?" without explaining what's wrong or showing your car.

cloud hill
#

Is it possible to have a task always run on a specific date? For example always on the first day of a month?

limber urchin
#

I know you can specify a list of times to run it, unsure if it works for days of the month

@tasks.loop(time=[datetime.strptime('12:00AM', '%H:%M%p').time(), datetime.strptime('12:00PM', '%H:%M%p').time()])
...

This example would run at 12AM and 12PM every day

cloud hill
drowsy hound
#

.rtfm audio

knotty surge
#

Hello all, I am trying to send a zip file I have created to a discord channel. I've made it a discord file however getting this: discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: expected str, bytes or os.PathLike object, not ZipFile

knotty surge
#

Files=my_zip

#

As a ctx.response

proud mason
knotty surge
#

Using the zip functions in python but if you give me 10 minutes I'll send the code. Just need to leave quick

knotty surge
# proud mason and how did you get `my_zip` ?
import zipfile

with zipfile.ZipFile("test.zip", mode="w") as archive:
            for file in glob.glob('sent/*.ytd'):

                    discord_prep = discord.File(file)
                    uniforms.append(discord_prep)

                    archive.write(discord_prep)

                    print("-- File to Send --")
                    print(file)
                    print("- File to Send Array -")
                    print(uniforms)

            # Used to be sleep for 10
            await discord.asyncio.sleep(2)

            print(uniforms[0])

        await ctx.send(
            file="test.zip"
        )

Error: Application Command raised an exception: TypeError: stat: path should be string, bytes, os.PathLike or integer, not File

drowsy hound
#

trying to stream music from youtube to the voice channel using a Lavalink node, but when I satrt the bot I get this error "Connection Failure: 500, message='Invalid response status', url=URL('https://lavalinkinc.ml:443')" . Where can I find other lavalink nodes?

limber urchin
drowsy hound
#

mhh so no music bots at all anymore?

limber urchin
#

and you obviously can't stream music you don't have rights to

wintry cosmos
#

Any advice on how to connect Bot with MongoDB database? IIRC you just have to pip install motor since pymongo and pymongo[srv] are included?
And for import in my .py file i have
from motor.motor_asyncio import AsyncIOMotorClient but it say that following marked area "mongodb+srv" isnt defined and throw an error.

async_client = AsyncIOMotorClient(**mongodb+srv**://xNiKERAGEx...)
drowsy hound
limber urchin
drowsy hound
#

ok, perfect, but how?

limber urchin
drowsy hound
#

Do I need the lavalink thing?

dim cape
limber urchin
young bone
silver moat
limber urchin
#

This would also apply to online services

proud mason
#

But tbf pycord doesn't enforce tos. Its upto the bot devs to use what they want

dim cape
limber urchin
# dim cape

Bro, your screenshots are absolutely useless. Show us the error.

wintry cosmos
dim cape
#

What 403 forbidden mean and how can i error handle it

limber urchin
#

But it doesn't change the fact that it's against ToS. A lot of developers lost their bot's verified status because they had music streaming on them

proud mason
silver moat
dim cape
#

What 403 forbidden mean and how can i error handle it

proud mason
#

Hah

limber urchin
silver moat
proud mason
# dim cape

Your bots highest role isn't higher than the users highest role

wintry cosmos
west venture
#

@everyone this is not @everyone ping but i need help 😎
code

    await user.send(embed=senimase)
    review_channel = bot.get_channel(c.review_channel)
    if str(ratings) == "1":
        print("one")
        stars = "⭐" 
    elif str(ratings) == "2":
        print("two")
        stars = "⭐⭐"
    elif str(ratings) == "3":
        print("three")
        stars = "⭐⭐⭐"
    elif str(ratings) == "4":
        print("four")
        stars = "⭐⭐⭐⭐"
    elif str(ratings) == "5":
        print("five")
        stars = "⭐⭐⭐⭐⭐"

    messagess = discord.Embed(
        title="Review",
        description=f"**Services Provided:** {role_ping}\n\n**__Freelancer__**\n{ctx.author.mention}\n\n **Review by**{user.mention}\n {stars} \n{user_review.content}",
        color= discord.Color.green(),
        timestamp=datetime.datetime.utcnow()
    )
    messagess.set_footer(text="• Xlereaon Services")
    
    await review_channel.send("stop reading this and solve my error")

Error

Command raised an exception: UnboundLocalError: cannot access local variable 'stars' where it is not associated with a value
wintry cosmos
#

So did any of you guys connected a MongoDB to your bot? I guess sqlite is better?

west venture
dim cape
west venture
limber urchin
#

You should use whatever suits your use case the best. There is no "better" option, only more suitable.

limber urchin
wintry cosmos
#

More user friendly, better overview, at least IDK whats crucial for a "good" database. I just heard sqlite is most commonly used so i thought of that its better

proud mason
west venture
silver moat
#

it's funny because discord uses non-sql things

limber urchin
silver moat
#

they used to use mongodb then switched to casandra

limber urchin
limber urchin
#

aka millions of messages every week

proud mason
wintry cosmos
#

I already choose mongodb but i can really understand why people are just storing data in .json files

proud mason
#

Yeah but json sucks as a db

silver moat
#

json can go die

#

because js can go die

wintry cosmos
#

😄

limber urchin
#

?tag nojson

obtuse juncoBOT
#

Why not to use json files for data storage
JSON files are commonly used to store data that is read by a program, however, they are unsuitable for storing dynamic data due to a number of reasons.
It is recommended to use a DBMS (Database Management System) as they come with optimized technologies for storing and retrieving information.

Advantages of using a database:
- Database tables can be related, making it easy to separate your information into multiple tables and only fetch what you need
- Databases allow you to use a query/data processing language to make complex data operations easier with less code
- One misplaced character will corrupt an entire file. A database very rarely experiences corruptions due to their automatic handling of data integrity
- Transactions in SQL databases allow you to revert unwanted changes and prevent data corruption in the case of an error
- Databases have support for indexes, allowing retrieval of some data to be extremely fast
- It is very easy to update existing data in a database, as opposed to re-writing a file
- Databases are reliable

Popular database management systems:

  • SQLite3 (File based, no need for a server setup, SQLite is the most used database engine in the world)
  • MongoDB (Stores data in documents a similar manner to JSON format, easy for beginners)
  • PostgreSQL (Very popular and robust SQL based database management system)
  • MySQL (Another popular SQL based system, good start for learning SQL)
proud mason
#

What issues are you having with using mongo?

west venture
#

Command raised an exception: UnboundLocalError: cannot access local variable 'stars' where it is not associated with a value
what does this error even mean?

west venture
wintry cosmos
#

No issues at all. I guess its just a bit harsh for setup. I watch the third video now the other ones were not very helpful.
I know its better to store things in DB thats why im changing to it, but yk its like being clinging to your habits.

limber urchin
#

Your question is easily solved by learning the basics of Python

west venture
hallow blaze
silver moat
limber urchin
wintry cosmos
#

If you want a helper which doesn’t contradict ask chatgpt lol but doesn’t expect learning anything from it

silver moat
wintry cosmos
silver moat
wintry cosmos
# west venture it useless

Not useless but you’re just not learning coding from it. The code which is supplied is good (most likely)

silver moat
#

or something like that

wintry cosmos
#

Includes pymongo and srv

west venture
limber urchin
#

it's of course not just going to give you a complete answer

west venture
silver moat
limber urchin
#

Right now ChatGPT is a great tool for developers to figure out tedious/difficult obstacles

wintry cosmos
#

I do use EnfusionScript for a Game im modding for and i was very surprised about the good code it supplies. Ofc you have to change something here and there but especially for difficult calculations its very good

west venture
silver moat
limber urchin
rare ice
# silver moat that likely will change one day

AI can’t replace humans entirely. For example, sports. It wouldn’t be interesting to watch robots try and tackle into each other and always know where the ball is, since they’re preprogrammed. Humans have discretion, AI will only have preprogrammed things to do and say, while we can make a decision on the circumstances. So I think AI won’t be able to replace humans entirely, and I hope not at all.

I have some magnets ready in case a robot tries to take over my house oldsmiley

silver moat
rare ice
#

We will ultimately be street-smarter than AI.

stark walrus
#

can bots log forum channel messages atm

woeful spindle
#

?tag tias

obtuse juncoBOT
tribal bough
#

how to add default permission to a slash command group (example please)

stark walrus
#

Unless I ping the bot

limber urchin
#

That means you don't have message content intents

stark walrus
#

I have it

#

I use discord.Intents.all() method

silver moat
stark walrus
silver moat
#

.rtfm discord.Thread.

silver moat
#

.rtfm SlashCommandGroup

tribal bough
#

there is a check parameter in SlashCommandGroup but i am confused how to use it...

#

and i also tried default_member_permissions but it didn't worked ...

woeful spindle
#

what doesn’t work?

tribal bough
silver moat
tribal bough
limber urchin
#

"example", more like code for you to copy/paste doggokek

tribal bough
woeful spindle
#

.

silver moat
tribal bough
#

aa i am giving condition in commands now instead of group (i just to explore pycord function by adding permission into group itself)

anyways thanks for the check example

proud pagoda
#

Hm, when I'm setting the thumbnail to a gif, it only shows the first frame

young bone
proud pagoda
#

Url

young bone
#

Its weird because I have an Embed with a thumbnail gif

limber urchin
#

It's not just a reduced motion setting on Discord or something? GIFs should definitely work for thumbnails

wintry cosmos
#

Any ideas how to display

Username: value
Wert: value
Gutscheincode: value

if its stored in db['Gutscheine] like this:

inputs = {
        'User' : str(member.id) ,
        'Username' : str(member.name) +"#"+ str(member.discriminator) ,
        'Gutscheincode' : Gutschein ,
        'Wert' : wert
      }

i tried show_all = collection.find_one() and print it but i dont want the User info nor the id.

#

I saw its possible to check filter but didnt understand the docs

proud mason
#

print(f"Username: {show_all['Username']}")

full basin
#

Or use a for loop to make it dynamic

proud mason
#

mhm

#

and have the keys you want to print in a list

young bone
#

Use UserID

#

If you change your name, it will not find it anymore

wintry cosmos
wintry cosmos
young bone
#

Always use the User ID and not the name

#

Same for roles and Channels

wintry cosmos
#

Yeah I remember same for people who left. My ban conmand is also with id

lethal valve
lethal valve
#

How

#

I keep failing

young bone
lethal valve
#

Thanks

tough briar
silver moat
#

this is why you use logging?

limber urchin
marble obsidian
#

is there any way to apply this to my bot?

limber urchin
#

It could be anything from an issue with your code to your host being bad. We don't know

limber urchin
serene spindle
limber urchin
#

And verification, yeah

marble obsidian
#

its a private bot and some people are struggling to use slash commands

limber urchin
#

If it's a private bot it shouldn't be too hard to tell them how to use it then, no?

marble obsidian
silver moat
#

use bridge commands?

marble obsidian
#

even with a video tutorial posted

marble obsidian
limber urchin
silver moat
undone falcon
#

Is there a way to check if my bot has manage role permissions in a specific guild ?

proud mason
#

.rtfm bot_has_permission

winter condorBOT
proud mason
#

or this

undone falcon
#

thanks !

undone falcon
#

how do you know what is the permission number ?

#

for exemple what would be "manage role" number

rare ice
#

.tag discord.Permissions

winter condorBOT
#

Tag not found.

rare ice
#

.rtfm discord.Permissions

undone falcon
#

yes I am on that page already

rare ice
#

or use the permissions calculator

patent sentinel
#

guys, is there a way to send ephemeral messages from getting messages in on_message?

proud mason
stark walrus
#

Component custom id cannot be duplicated
When I try to do emb = interaction.message.embeds[0].copy()

stark walrus
#

Oh nevermind sorry

#

I found out my mistake in the code a few mins ago

proud mason
#

Ah lol

stark walrus
#

How to make a button on timeout be disabled?

copper dew
stark walrus
#

tyy

copper dew
fringe socket
#

Um, what's the model for the member that used the select menu?

fringe socket
#

nvm i found it

limber urchin
#

Just fetch the images from the json file and use random.choice to pick one

#

If you've never coded before, you should not be making a Discord bot

#

read rule 1 in #help-rules

empty kraken
#

Hey guys, how can i edit a view in an ephemeral message? (with followup)

empty kraken
proud mason
#

Indent it inside the cog

#

Yeah and call it like self.set_emoji_quiz(...)

#

No no
Not while defining it

While calling it

#

Outside the class. Some people like to put it in a separate file of thier own

#

No worries lol

#

self.bot

#

Use that

#

Inside the cog right

#

Accept self as the first parameter in the functions

#

It would be a good idea to revisit some oop tutorials on python

north gorge
#

Can anyone copy/paste me an example of a user_command with a check for having a certain role?

fringe socket
#

?tag codeexamples

obtuse juncoBOT
north gorge
#

I don't think the docs are very clear how the checks parameter should work, doesn't seem like an unreasonable "quick question".

proud mason
#

Oh wait. I think you have defined the functions in the cog but are calling them from the View

#

Am i right?

wooden lodge
#

Is V3 stable enough for a Server with 50.000 Members?

dapper flare
#

i need help

#

how do i send a message to author's dm, also being in a while loop

dapper flare
# wooden lodge member.send
while True:
        def check_ratings(m: discord.Message):
            if int(m.content) > 0 and int(m.content) <= 5:
                return True
            else:
                user.send("I'm sorry, Please enter a number between 1 to 5") # getting error here
        ratings = await bot.wait_for('message', check=check_ratings, timeout=None)
        if (ratings.content).isdigit():
            await user.send(embed=review)
            break
    print(ratings.content)```
#
  userr.send("I'm sorry, Please enter a number between 1 to 5")
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
#

this is the error

wooden lodge
#

are you using a def in a while 💀

dapper flare
#

sorry i guess

wooden lodge
#

user.send("I'm sorry, Please enter a number between 1 to 5")
await user.send("I'm sorry, Please enter a number between 1 to 5")

dapper flare
# wooden lodge > user.send("I'm sorry, Please enter a number between 1 to 5") **await** user.se...

uh so how do i make it work?

def check_ratings(m: discord.Message):
        if int(m.content) > 0 and int(m.content) <= 5:
            return True
        else:
            user.send("I'm sorry, Please enter a number between 1 to 5")
    while True:
        ratings = await bot.wait_for('message', check=check_ratings, timeout=None)
        if (ratings.content).isdigit():
            await user.send(embed=review)
            break
    print(ratings.content)```
```RuntimeWarning: coroutine 'Messageable.send' was never awaited
  user.send("I'm sorry, Please enter a number between 1 to 5")
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
#

can't use await in def

proud pagoda
#

And then when you run it, you do await check_ratings(...)

wooden lodge
#

@proud pagoda How do you got Helper Role?

dapper flare
#

okay

proud pagoda
wooden lodge
#

Ig you do that actively

proud pagoda
#

Yeah

loud holly
#

What is this called again? I forgot the term for it

Embed_Fields: list = [Embed_Field[Data] for Embed_Field in Embed_Dict.get("fields") for Data in Embed_Field if Data != "inline"]
loud holly
proud mason
#

Give it about a year

#

Can you show the full file so i understand what's going on

young bone
#

do you send a modal with a modal?

limber urchin
#

If you're trying to timeout the server owner, you can't

limber urchin
#

And for how long are you trying to time them out for?

marble obsidian
fervent cradle
#
import discord
import aiohttp
import random
from discord.ext import commands

def random_number():
    return str(random.randint(0,900))

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


    @commands.slash_command(
        name="guess_the_pokemon",
        description="Begins a game of guess the Pokemon"
    )
    async def guess_the_pokemon(self, ctx, prize : str, channel : discord.TextChannel = None):

        await ctx.defer()

        if channel != None:
            event_channel = self.bot.get_channel(channel.id)
        else:
            event_channel = self.bot.get_channel(ctx.channel.id)

        async with aiohttp.ClientSession() as session:
            pokemon_api = await(await session.get(f"https://pokeapi.co/api/v2/pokemon/{random_number}")).json()
        
        pokemon = pokemon_api["species"]["name"]

        embed = discord.Embed(
            title = "Guess the Pokemon!", description = f"The first person to guess the Pokemon below receives the prize:\n**{prize}**", color = discord.Color.green()
        )
        embed.set_image(url=pokemon_api["sprites"]["front_default"])

        await event_channel.send(embed = embed)

        while True:
            msg = await self.bot.wait_for("message")
        
            if msg.content.lower() == pokemon.lower():
                await event_channel.send(f"{msg.author} guessed right!")
            else:
                await event_channel.send(f"{msg.content} is wrong, the answer was: {pokemon}")

def setup(bot):
    bot.add_cog(GuessThePokemon(bot))

anyone know why msg.content is always showing up empty?

limber urchin
fervent cradle
#

yea

limber urchin
#

Enabled in both the code and the dev portal?

fervent cradle
limber urchin
#

also why the while True? Your guessing game is never going to end?

young bone
fervent cradle
limber urchin
#

Dude stop spamming your question

#

You've already posted here twice. and made a thread

#

Stick to the rules or leave

marble obsidian
proud mason
#

Move the functions you want inside the class you want to use them

#

Ig

#

You can get bot instance from interaction.client

wintry cosmos
#

Chat GTP just told me that "The Wix API is not available for Python, so it is not possible to use Python to create a custom endpoint for your server-side script on a Wix website." so its not possible to request a data from my Wix Website and display it in DC via my .py Bot?

limber urchin
#

That's not really related to Python or your bot at all, that's an issue with Wix.

#

You're better off asking their support, as this server has nothing to do with that.

wintry cosmos
limber urchin
#

Do you have message content intents?

unreal tangle
#

nope i didnt
thx, it works now 👍

winter dagger
#

Anyone have an easy way to send paginated embeds outside of an interaction? It seems like the built in paginator.send requires a ctx and paginator.respond requires a discord.Interaction, which makes sense.

full basin
winter dagger
# full basin What else is not a ctx or a interaction?

I've built an alert system which sends embeds to channels long after they've been set. So I fetch the channel from the channel id and send the embed using channel.send. It doesn't seem like a ctx is involved in any of that but I could be missing it.

fervent cradle
#

How can I make a slash command that only works on servers not users dm??

silver moat
#

.rtfm guild_only

fervent cradle
#

tnx

river dove
#

guild.get_member is returning None these are my intents configuration:

#

i have both intents enabled on the dev portal too

fervent cradle
#

does anyone know how to tell if a message has already had .delete() called on it

#

I have multiple conditions in an on_message listener that might lead to message deletion, it doesn't actually affect the bot but getting errors in console is kind of annoying

silver moat
#

.rtfm on_message_delete

winter condorBOT
silver moat
fervent cradle
#

I'm calling from within an on_message function, just need to be able to tell if the message is already deleted

silver moat
#

try-except?

fervent cradle
#

cancer but I guess it would work

fervent cradle
#

aint nobody reviewing this code other than me skullspawn

young bone
# river dove

if you still get it, than the bot cannot find the member

silver moat
#

is guild.members empty?

proud cargo
#

How do I add the member intent to discord.Intents.default()

silver moat
#

?tag intents

obtuse juncoBOT
#

https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-intents

import discord
from discord.ext import commands

# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True  # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content 
intents = discord.Intents.default()

# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True  # Required for prefix commands >= 2.0.0b5

# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()

# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
Discord Developer Portal

Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.

fervent cradle
#

How can i get the user who made the change on the on_guild_channel_update event? For example I would like to display the user who renamed a channel.

fervent cradle
#

Thanks

bold notch
#

.embeds

lapis jolt
#

I've been trying to record conversation in a voice channel and I'm using discord.sinks.WaveSink(). When I iterate through sink.audio_data.items() in the callback I'm only seeing the first 5 minutes of audio. Is there something I need to do to get the full conversation?

proud mason
lapis jolt
proud mason
#

but its upto you

bold notch
#

Is there any problems running two instances of the bot to the same bot account? They both only use slash commands and technically dont have anything overlapping.

proud mason
#

Including interactions

#

if bot instance 1 has f, a, b cmds
and bot instance 2 has f, x, y cmds

then
interactions for f, a, b, x, y will go to both

#

both instances will try and send a callback for f. the one with slower connection would fail

#

for a, bot1 will successfully process it, but since it would be missing in bot2, bot2 will try to remove it from discord. this can be averted if you set auto_sync_commands to false

boreal abyss
#

can i do modals in pycord?

#

form modals.

proud mason
boreal abyss
#

to fill

proud mason
#

yes

errant craneBOT
#

Here's the modal dialogs example.

boreal abyss
#

example or docs

proud mason
#

see that

#

.rtfm Modal

boreal abyss
#

@silver moat is a MrBeast 💀

#

tysm

#

thanks om

proud mason
#

np 🙃

boreal abyss
#

await value.callback(interaction)
File "C:\Users\يولين\Downloads\rwg.py", line 40, in callback
user_id = str(interaction.context.author.id)
^^^^^^^^^^^^^^^^^^^
AttributeError: 'Interaction' object has no attribute 'context'

#

@proud mason

boreal abyss
#

kk

proud mason
#

read the docs when blobpain

boreal abyss
#

💀

#

why would i read if i have daddy om

boreal abyss
#

@proud mason discord modals limited to 5 questions??

proud mason
#

also, dont ping members for help blobpain

dapper flare
#

hey can anyone tell me what this error means? discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UnicodeEncodeError: 'charmap' codec can't encode character '\u2665' in position 13749: character maps to <undefined>

boreal abyss
#

age_group = "Unknown"
if member is not None:
print(role.name for role in member.roles)
if "18-21" in [role.name for role in member.roles]:
age_group = "18-21"
elif "21-51" in [role.name for role in member.roles]:
age_group = "21-51"
elif "100-900" in [role.name for role in member.roles]:
age_group = "100-900"

why doesnt this work. and stayes as "unkown" i have intents. in dashboard

#

any intents must be added in code?

#

@proud mason last thing istg

simple canopy
#

you have guild members intent, right?

boreal abyss
#

in dashboard

simple canopy
#

🤨

#

?tag intents

obtuse juncoBOT
#

https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-intents

import discord
from discord.ext import commands

# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True  # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content 
intents = discord.Intents.default()

# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True  # Required for prefix commands >= 2.0.0b5

# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()

# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
Discord Developer Portal

Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.

boreal abyss
#

intents = discord.Intents.default()
intents.message_content = True
intents.members = True
that is my intents in cod

simple canopy
#

and you have those enabled on discord developer portal?

boreal abyss
#

yh

simple canopy
#

and this aswell, i hope

boreal abyss
#

ofc..\

simple canopy
#

just to be sure, well

boreal abyss
#

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

simple canopy
#

at least, you can create one single list with all roles you need, instead of creating at everytime

#

and, you can print it out to check availability of all the roles

boreal abyss
#

i tried but my brain glitched like

age = ["3333","33322","32211"] -- ID*S
now i want to check which one on users acc

simple canopy
#

well uh

#

using id's is preferable

#

but they should be an integer, not string

boreal abyss
#

WTV, just the point is how to check

simple canopy
#

same as you did before, but i suggest you making an variable with your id list

#

if ID in list

#

blah blah blah

boreal abyss
#

kk

dapper flare
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: SSLError: HTTPSConnectionPool(host='steamcommunity.com', port=443): Max retries exceeded with url: /inventory/76561198055800013/730/2?l=english&count=5000 (Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:992)')))
how do i fix this?

boreal abyss
#

@simple canopy yo

young bone
boreal abyss
#

what do you thing member should be

#

member = user_id?

simple canopy
#

discord.Member

#

rtfm

boreal abyss
#

where is the docs for this

simple canopy
#
boreal abyss
#

member = ctx.guild.get_member(user_id)

#

?

simple canopy
#

if you have an member object, you don't need it

#

but in general, yes, it's one of the ways to get it

boreal abyss
#

it fails still

#

it makes member = None

simple canopy
#

it's not cached then

young bone
#

do you have intents?

simple canopy
#

either it's not on guild anymore, or it fails to cache it

boreal abyss
boreal abyss
young bone
#

code and website?

boreal abyss
#

yh

#

soososo

simple canopy
#

give full code

boreal abyss
#

import discord
from discord.ext import commands
import json
intents = discord.Intents.default()
intents.message_content = True
intents.members = True

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

@bot.slash_command()
async def information(ctx, user_id: str):
try:
member = ctx.guild.get_member(user_id)
age_group = "Unknown"
if member is None:
print("Member object is None")
if member is not None:
print([role.name for role in member.roles])
if "18-21" in [role.name for role in member.roles]:
age_group = "18-21"
elif "21-51" in [role.name for role in member.roles]:
age_group = "21-51"
elif "100-900" in [role.name for role in member.roles]:
age_group = "100-900"

#

the rest is not valuable.

simple canopy
#

what's user_id

#

is it an option

boreal abyss
simple canopy
#

if it is, it shouldn't be str

#

id's are integers

boreal abyss
#

ik

#

but "DISCORD' SAYS it must be str for it to work on slashcmd

#

wait lemme try

simple canopy
#

not it shouldn't

boreal abyss
#

cuz i got the error 'enter right int

simple canopy
#

well, tbf

#

you can replace it with discord.Member

#

instead of str and id at all

#

this will do

#

there is an Member option type, so you can basically select members ifp

#

if it doesn't work, try following documentation on discord.Option and examples from github repo

boreal abyss
#

iactually got it from docs wi\th that error

young bone
simple canopy
#

i hope it'll work

summer fulcrum
#

How can I make a prefix for a bot that will respond to both a large and a small letter

simple canopy
#

make 2 prefixes

simple canopy
#

or that

#

¯_(ツ)_/¯

boreal abyss
#

should i replace\

simple canopy
#

user_id peepoBlink

#

i mean, rename it

#

aswell

boreal abyss
#

hold up

#

it will fuck my json i need a id entry

simple canopy
#

you can get an user id

#

from

#

discord.Member

#

please

boreal abyss
#

the docs are too complicatedd

young bone
#

no?

boreal abyss
#

like fr everything is mixed together

simple canopy
#

then go cry in a pillow

#

👍

boreal abyss
#

wtf...

simple canopy
#

you don't need an source code

boreal abyss
#

dady gigabite

#

or gigachad

simple canopy
#

;/

#

no

#

learn stuff yourself or you won't be able to do stuff

#

gl

boreal abyss
#

yk the way i be learning from you is the same from docs, i just not comfortable with the docs pycord, is giving. i came accross alot of docs. but the better i saw was easy. this one is complicated, not straight to point, and just ....

#

you would actually be saving my time, and doing your job, your not even spoonfeeding

#

and ill be happy

#

and kiss u

simple canopy
#
proud mason
#

Rtfd 💀

boreal abyss
#

...

#

why are you mean bruh

simple canopy
#

we are just trying to say

#

that you gotta learn stuff yourself

#

to do stuff

#

we can't just spoonfeed everything to you

boreal abyss
#

can u just answer this thing for me and ill never ask again.

simple canopy
#

try to, at least, try to read

boreal abyss
#

NOT spoonfeeding, is im asking how to call the userid from discord.member

#

a aint asking you to code a bot

boreal abyss
simple canopy
#

i said everything already

#

💀

boreal abyss
boreal abyss
#

or im wrong 💀

simple canopy
#

you're right

#

go code your stuff

#

good luck

boreal abyss
#

ty ig

#

ahaa, type object 'Member' has no attribute 'ID'

#

💀

#

small id?

proud mason
#

Yes

boreal abyss
#

Member object is None
ERROR LOGS: '<property object at 0x000002AD14051990>'

#

?

proud mason
#

Wtf did you do 💀

boreal abyss
#

    member = ctx.guild.get_member(discord.Member.id)
    age_group = "Unknown"
    if member  is None:
        print("Member object is None")
    if member is not None:
        print("roles", [role.name for role in member.roles])
        if "18-21" in [role.name for role in member.roles]:
            age_group = "18-21"
        elif "21-51" in [role.name for role in member.roles]:
            age_group = "21-51"
        elif "100-900" in [role.name for role in member.roles]:
            age_group = "100-900"    
    with open("users.json", "r") as f:
        users = json.load(f)
proud mason
#

I want to cry sorry

boreal abyss
#

am i really that dumb

boreal abyss
errant craneBOT
#

Here's the slash options example.

proud mason
#

Use the member option

#

So you wouldnt need to use get_member

quartz iron
#

I'm trying to get my user id and write it into mysql db.
The problem occurs at the moment when I try to write this data (31-34). It writes random id into db (2147483647), but i need to write my user id (1003694956919148625). Any ideas?

class MyModal(discord.ui.Modal):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)

        self.add_item(discord.ui.InputText(label="Name"))
        self.add_item(discord.ui.InputText(label="Gender"))
        self.add_item(discord.ui.InputText(label="City"))
        self.add_item(discord.ui.InputText(label="Description", style=discord.InputTextStyle.long))

    async def callback(self, interaction: discord.Interaction):
        id = interaction.user.id
        print(id)
        cursor = connection.cursor()
        cursor.execute(
            "INSERT INTO users (id, name, gender, city, description) VALUES (%s, %s, %s, %s, %s)",
            (id, self.children[0].value, self.children[1].value, self.children[2].value, self.children[3].value)
        )
        connection.commit()```
quartz iron
#

In console print id is correct

#

But in db - it isn't

boreal abyss
#

use json its lifesaver

proud mason
#

No bro

#

Dont

#

.nojson

winter condorBOT
#

JSON is a convenient and easy-to-read data storage protocol that's widely accepted by most programming languages. However, we caution against its use for storing and retrieving data in an asynchronous environment like a Discord bot. Don’t use json!

  • It's a file-based data storage, which makes it vulnerable to race conditions
  • You'll need to implement your own synchronization primitives to avoid corrupting data
  • If you're not careful, you could accidentally wipe your entire JSON file.

Solution? Use a database. Recommended schema are SQLite, PostgreSQL, and MongoDB.

  • Async libraries exist on pypi for each of these
    sqlite -- aiosqlite (or Danny's wrapper, ?tag asqlite)
    postgresql -- asyncpg
    mongodb -- motor
  • Databases organize your data into tables, and are fast at inserting, retrieving, and removing records
  • You can impose uniqueness constraints to ensure against duplication
  • The Python libraries enforce synchronization for you
  • The query language is intuitive, you can get running with simple queries in just a few hours!
boreal abyss
#

if u have a good hosting, encryption, you dont have to worry.

proud mason
north gorge
#

how does encryption.. ... json..

boreal abyss
#

values

proud mason
#

SQL is not that hard

north gorge
#

yeah man, just use sqlite

boreal abyss
#

mehalready coded json

north gorge
#

well, when that blows up, remember sqlite

boreal abyss
north gorge
#

not yet gigachad

#

there's always tomorrow

proud mason
#

Also, use an async driver

north gorge
#

oh, so don't use sqlite3?

boreal abyss
#

💀

north gorge
#

using sqlite 3

boreal abyss
#

complicated stufffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff

proud mason
#

Also yes, do not use sqlite3
Use asqlite or aiosqlite

#

Or straight up use an ORM

boreal abyss
#

huh

north gorge
#

hmm, well I know what I'm doing this morning then

#

if our economy.db blew up everyone would kill me

proud mason
#

Daily backups? 👀

north gorge
#

uh.. yes... of course..

boreal abyss
#

lie detect

boreal abyss
north gorge
#

Om is very helpful

proud mason
#

Ty 🙃

proud mason
north gorge
#

phew, converted to aiosqlite

#

now to watch it all day hoping I didn't break anything

north gorge
#

How does the checks parameter work on a user_command? I'm not entirely sure what to do with it.

quartz iron
#

I FIXED THIS SHIT

#
ALTER TABLE users MODIFY COLUMN id VARCHAR(255);
ALTER TABLE users MODIFY COLUMN name VARCHAR(255);
ALTER TABLE users MODIFY COLUMN gender VARCHAR(255);
ALTER TABLE users MODIFY COLUMN city VARCHAR(255);
ALTER TABLE users MODIFY COLUMN description VARCHAR(255);
#

And all is fine now

#

LOOOOOL

#

I spent all day on this

proud mason
#

but wait

proud mason
#

especially id

#

should be BIGINT tbh

quartz iron
#

Oh

#

💀

knotty void
#

How can check if a option of a slash command has been used?

proud mason
proud mason
#

Unless you changed that

fervent cradle
#

do you guys know how do i edit the response i tried await ctx.edit("Test 2") but i got this error: TypeError: edit_original_response() takes 1 positional argument but 2 were given

knotty void
fervent cradle
#
await ctx.edit(content="Test 2")
#

like this?

proud mason
#

Yes

#

.tias

winter condorBOT
coarse spire
#

How can I read a .env file in the .gitignore folder to pass a token?

silver moat
coarse spire
silver moat
#

what does your gitignore file look like?

#

uhh I've only seen a .gitignore file

#

not a folder.

coarse spire
young bone
#

what?

silver moat
#

these people explain better than me ^

coarse spire
#

ah, I get it now

#

thanks

drifting birch
#

Is there a way to have a list of roles as input in discord.Option? Or do I have to have the user manually mention roles in a str input field?

full basin
#

discord.Role

limber urchin
#

You can not select multiple roles in one option if that's what you're asking

drifting birch
#

ok thx

silver moat
#

at that point just use a role select menu

full basin
#

True

drifting birch
silver moat
drifting birch
#

interesting

silver moat
#

you are thinking of a string-select menu

proud mason
#

.rtfm role_select

winter condorBOT
proud mason
#

1st one

coarse spire
silver moat
#

does your .env look llike

DISCORD_TOKEN=INSERT_TOK3N_H3R3
```?
#

with no spaces

coarse spire
#

but, well, with my actualy token

#

so what am I doing wrong? :/

limber urchin
#

Is your env file in the root folder of your project?

coarse spire
#

none of my files are in a folder even

limber urchin
#

??

#

Could you show your file structure?

coarse spire
limber urchin
#

Can you screenshot your env file, and blur out the token?

#

Also don't use json as a database

coarse spire
#

ok

silver moat
#

are you using replit?

coarse spire
#

no

#

I did before, but I switched over

limber urchin
#

Switched over to what?

silver moat
#

where are you getting the error, local machine, or host?

silver moat
limber urchin
#

Did you add your .env file to the host as well?

coarse spire
limber urchin
#

Visual Studio Code is not a host

coarse spire
#

ah, as a host I use sparkedhost

#

I couldn't afford anything better 😔

limber urchin
#

Your host probably handles environment variables in some weird way then. Not much we can do to help, contact their support

coarse spire
#

😦

#

ok, well, thank you still

proud mason
#

Pass a relative location

#

And not an absolute location

coarse spire
#

oh wait

#

I fixed it

proud mason
#

Nice

#

how did you fix 👀

wind jay
#

how to add a cooldown to a interaction?

fervent cradle
#

what does client's internal cache mean?

limber urchin
#

It means the internal cache managed by the library

proud mason
errant craneBOT
#

Here's the cooldown example.

fervent cradle
wind jay
proud mason
wind jay
#

okay

proud mason
#

wait i think you can use pycord internal stuff to make things slightly easier

#

ok no it would be more difficult to use that lmao

dim cape
#

What do persisent views do

blissful hazel
errant craneBOT
#

Here's the persistent example.

dim cape
blissful hazel
boreal abyss
#

embed = discord.Embed(
title="New Suggestion!",
fields=[
discord.EmbedField(
name="By", value=f"<@{user_id}>"
),
discord.EmbedField(
name="Suggestion", value=f"{self.children[0].value}"
),
discord.EmbedField(
name="Benifits!", value=f"{self.children[1].value}"
),
],
color=discord.Color.random(),
)
test = await interaction.response.send_message(embeds=[embed])
await test.add_reaction('👍')
await test.add_reaction('👎')

NO REACTIONS GETTING ADDED? <- error

weak mural
#

using the slash_command decorator, the slash command just inherits the name of the function immediately afterwards, right? no way to do name=<whatever> like with @bot.command?

drifting birch
full basin
#

.rtfm interaction.response

winter condorBOT
full basin
#

You need the message

weak mural
#

i pull the command names from a list of vars at the top of the file (so I can change em easy), so nice that it works the same

#

Do you need the self? I thought it would just be def funcname(ctx)

drifting birch
silver moat
weak mural
weak mural
#

since I use @bot.command already it seems like I probably should just be able to switch that to @bot.slash_command and pass in the allowed server list and have it function.. I think. you can also do ephemeral responses to slash_commands too, right

#

I havent messed w/ ephemeral messages yet

silver moat
weak mural
#

I have a dict of serverids:channelids right now since I was using the old response method to do my commands. so I should just be able to pass in the keys to that dict

silver moat
#

You can use ephemeral responses in slash commands in addition to other forms on interaction.

weak mural
#

allowed_channels.keys() or whatever method

silver moat
weak mural
#

at least thats what I would think

weak mural
#

I'm not sure on the channel thing - I'm just doing a check if msg.channel.id is in dict[msg.guild_id], but maybe there's some prettier way to make a command only in one channel on a given server?

#

Like I said I did a partial rewrite of my bot that used the older on_message() way of doing things, eggdrop style lol

#

so some of the stuff on that bot carried over

silver moat
#

.rtfm on_interaction

silver moat
#

may be useful

weak mural
#

yeah, I was just looking at some of the kwargs that can go with slash_command. checks keyword might be what I need there

#

But I'm not super worried about that until I get the new version up and going with the slash commands anyways

#

it mostly works now, but I have to find all the places that ints are getting turned into strings and recast them. it's been a fun little minefield :D

silver moat
#

good luck.

#

feel free to ask for help

weak mural
#

Yup. Honestly most of the issues I've had were with the game logic I wrote for the bot, and not the bot library itself. seems pretty intuitive

silver moat
#

That’s the point :)

weak mural
#

it's nice!

boreal abyss
#

how can i make a button never expires, clickable by everyone

errant craneBOT
#

Here's the persistent example.

boreal abyss
#

invalid

#

@silver moat .

errant craneBOT
#

Here's the persistent example.

weak mural
#

Do we have any example/showcase bots here? Digging through the api I"m kinda curious on how dialogs that accept input work on the discord user's end. dont remember ever seeing one of those

boreal abyss
#

hmm cant understand can u explain

silver moat
#

I think the command is +modal test

boreal abyss
silver moat
weak mural
#

yeah I found it, /modaltest - not exactly what I was looking for tho :( What I'd love is for there to be a way to put a text box into an embed, where people could type a guess into the box and click a button to have it submitted for the round

silver moat
weak mural
#

Dunno if there's any functionality for an embedded one like that

#

Gotcha. That's okay, /guess 123 should work just fine, i just was thinkin that would be a kinda slick way to do it lol

silver moat
weak mural
#

Having a popup box is a little much for what I'm using it for, so i"ll just stick with a /guess command. I WAS using !guess 123 and having the bot delete the message (since I want the guesses to be private), but that's a little janky lol

silver moat
#

alright

graceful nebula
#

Is it possible to have a command group and use the groups name as a command (if that makes sense)?
For example, have both of these be a command?

/rank
/rank top
full basin
#

No

graceful nebula
#

Okay thought so, wanted to double check. Ty!

young bone
#

./rank rank should work

graceful nebula
# young bone ./rank rank should work

My problem is people are used to !rank and I want to separate it out for its slash command by doing a /rank and /rank search, but I'm gonna have to do it as /rank top & /rank search instead I guess aha

lament crown
#
print(f"We have logged in as ")

is there a way to add like a mention user to the bots would say we have logged in as bot#1234?

fringe socket
#

💀 Another one that didn't read them.

fervent cradle
#

How can i use deleted = await ctx.channel.purge(limit=amount+1) to specifically only clear messages by bots?

silver moat
fervent cradle
#

Thank you

lament crown
#

tysm just a squid

#

does anyone know how to make it in a command were u chose from the users on the server so like /idk user: then u put a name like that is that possible?

#

@fervent cradle how are u using ctx bc it won't work for me like are u using a different library or just a older python version?

lament crown
#

3.11.1 i think

#

3.10.9

fringe socket
#

I recommend using 3.8/3.10 for Pycote

#

*Pycord

lament crown
#

how do i chnage it?

fringe socket
#

Do you have a runtime.txt file?

lament crown
#

i don't think so

fringe socket
#

Create one in your bot folder, and type in either 3.8 or 3.10 in there

lament crown
#

ok then how do i get ctx in there bc pip install ctx does not work

#

do i just type that?

fringe socket
#

Bruh

full basin
#

Lmfao

#

Learn python

fringe socket
#

Are you trying to install ctx 🤣

lament crown
#

yes

full basin
#

Please do learn python

lament crown
#

i know it but i don't do stuff like this

full basin
#

You don't know it

#

#help-rules

lament crown
#

i have been doing python for 3 years

fringe socket
#

ctx is provided by discord which is the namespace of pycord v2

#

You don't need to install it

lament crown
#

oh ok

fringe socket
#
$ pip install py-cord
lament crown
#

i used to code python on a web based ide but trying to do python on local host now

#

ty sorry i am acting like a idiot with this i know a good bit but installing libraries is new bc i just switched running it on my pc not the cloud

#

ty for helping me

#

ModuleNotFoundError: No module named 'discord.enums' what does this mean getting a error with not changing the code and the error is within the library bc i don't have 3k lines of code

fringe socket
#

discord.Option?

#

Sometimes stuff you do in your code can cause errors in the library

#

It doesn't necessarily mean the library is at fault

lament crown
#

so should i restore it to the last save to see if that is the problem?

amber shale
#

what is the best way to get a bool value from modal or a url (i mean restrict user from typing else)

lament crown
#

from ..enums import AppCommandOptionType, AppCommandType, ChannelType, Locale
ModuleNotFoundError: No module named 'discord.enums'

#

that is the error

rotund current
#

Is it possible to extract the view from a message if you have the message ID? I know you can overwrite the view when editing a message, but can you pull the view out of a message, to add or remove things from the view?

proud mason
#

Or is that not your code but the library?

#

Show pip list

amber shale
proud mason
#

.rtfm View.from

winter condorBOT
proud mason
#

Yes ^

rotund current
#

Sweet. Thanks so much

proud mason
#

No worries 🙃

rotund current
#

I had been looking in the docs under the message, didn't think to look under view

lament crown
#

this is not normal something is wrong bc i installed this

amber shale
#

In embeds.0.url: Scheme "a" is not supported. Scheme must be one of ('http', 'https').
i am getting url from modal is there any way to stop user from typing something that is not url

lament crown
#

error message

#

from ..enums import AppCommandOptionType, AppCommandType, ChannelType, Locale
ModuleNotFoundError: No module named 'discord.enums'

proud mason
lament crown
#

wdym?

amber shale
proud mason
#

Go to your terminal

#

And run that cmd

lament crown
#

Package Version


aiohttp 3.7.4.post0
aiosignal 1.3.1
async-timeout 3.0.1
asyncio 3.4.3
attrs 22.2.0
certifi 2022.12.7
chardet 4.0.0
charset-normalizer 2.1.1
colorama 0.4.6
coverage 7.0.4
discord 2.1.0
discord.py 2.1.0
exceptiongroup 1.1.0
frozenlist 1.3.3
idna 3.4
iniconfig 2.0.0
multidict 6.0.4
numpy 1.24.1
packaging 22.0
peewee 3.15.4
Pillow 9.4.0
pluggy 1.0.0
pytest 7.2.0
pytest-cov 2.12.1
rand 0.3.0
requests 2.28.1
toml 0.10.2
tomli 2.0.1
typing_extensions 4.4.0
urllib3 1.26.13
yarl 1.8.2

amber shale
proud mason
lament crown
#

do i need pycord too

#

or should i switch over

amber shale
proud mason
amber shale
#

^

lament crown
#

did that

proud mason
lament crown
#

ok

amber shale
lament crown
#

@proud mason what is the import for pycord?

proud mason
proud mason
lament crown
#

it is white not cyan though

proud mason
proud mason
amber shale
#

🥲 ok thanks for helping

proud mason
#

What ide do you use? Vscode? Pycharm?

proud mason
lament crown
#

vscode

proud mason
#

That's fine

lament crown
#

i get this error when i run it @bot.tree.command(name="hello", description="say hello to me")
AttributeError: 'Bot' object has no attribute 'tree'

proud mason
#

.guide

winter condorBOT
lament crown
#

should i remove the command tree

proud mason
#

That's not how pycord implements app cmds

proud mason
lament crown
#

ok i will tmr ty for helping i gtg

proud mason
#

👍👍

rotund current
#

I am trying to work on some persistent buttons. Basing some of the code off of the button role example, I have the bot on loading the cog find the appropriate message from my database, getting the message, extracting the view from it and then adding the view from the bot, but even though when I print out the view on the console, it tells me there are the correct number of items in the view, when I click on the buttons, they don't function like they did before the restart, And I have confirmed that they do function before restarting the bot.

Here is the code:

@commands.Cog.listener()
    async def on_ready(self):
        print("4e Cog Loaded")
        # We recreate the view as we did in the /post command.
        view = discord.ui.View(timeout=None)

        engine = get_asyncio_db_engine(user=USERNAME, password=PASSWORD, host=HOSTNAME, port=PORT, db=SERVER_DATA)
        async_session = sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
        async with async_session() as session:
            result = await session.execute(select(Global).where(
                    Global.system == "D4e"))
            guild_list = result.scalars().all()

            for guild in guild_list:
                tracker_channel = self.bot.get_channel(guild.tracker_channel)
                last_tracker = await tracker_channel.fetch_message(guild.last_tracker)
                comp_list = last_tracker.components
                print(comp_list)
                view = discord.ui.View.from_message(last_tracker, timeout=None)
                print(view)
                self.bot.add_view(view, message_id=guild.last_tracker)
proud mason
#

View.from_message does not give you buttons with callbacks

rotund current
#

Well that would expalin it

proud mason
#

You should rather subclass and create the view fresh for every guild

rotund current
#

The problem I was running into with that is that the callback requires the application context to function, and I am running into the wall that I can't just recreate the buttons without the ctx

#

Is there a way to get the button with callback from the old message?

hallow oriole
#

Hello again, one quick question: What is the best way to get the id of a slash command for mentioning it? For example I want to create a custom help command, where all the commands are clickable with the /name:cmd_id markdown. I thought about fetching a list of all the commands that are registered by the bot and looping through it to get the right one, but it would be even better if I could fetch just a specific command by name. Is there a function that does that?

proud mason
rotund current
proud mason
rotund current
#

I was hoping there were easier options, but I may need to go down that route

proud mason
#

You can find regex patterns for urls on Google

#

Even the library has a few

coarse spire
#

ok well, I made a test file and copied the code from the pycord docs for cogs, so I added this to main; client.add_cog(greetings(bot))

and this to the cog;

    def __init__(self, bot):
        self.bot = bot
        self._last_member = None

    @commands.Cog.listener()
    async def on_member_join(self, member):
        channel = member.guild.system_channel
        if channel is not None:
            await channel.send(f'Welcome {member.mention}.')

    @commands.command()
    async def hello(self, ctx, *, member: discord.Member = None):
        """Says hello"""
        member = member or ctx.author
        if self._last_member is None or self._last_member.id != member.id:
            await ctx.send(f'Hello {member.name}~')
        else:
            await ctx.send(f'Hello {member.name}... This feels familiar.')
        self._last_member = member```

I get the error  NameError: name 'greetings' is not defined
proud mason
#

Rather than manually importing it

coarse spire
#

oh, ok

#

I'l try

coarse spire
#

ok, so I tried this

  client.add_cog(greetings(bot))

setup(client)
client.run(TOKEN)````and it doesn't work. am I doing something wrong?
#

I still get the error that NameError: name 'greetings' is not defined

fringe socket
#

hmmm

#

Did you import the cog?

copper dew
proud mason
#

And that's not how you make cogs

#

.guide

winter condorBOT
proud mason
#

Check the cogs section there

coarse spire
#

ok, well, now I'm getting this error; Extension 'cogs.greetings' raised an error: AttributeError: 'Bot' object has no attribute 'add_command', might that be cause I've defined it as Client instead of Bot?

proud mason
coarse spire
#

ah right

naive steppe
#

is there a way to do the following:
/checkroleperms [@role]
and have it return the permissions of the role?

results would be something like

has admin: false
has channel edit: true
ect ect
full basin
#

.rtfm Role.permissions

winter condorBOT
tribal bough
#

.rtfm discord.ui.channel_select

winter condorBOT
tribal bough
wintry cosmos
#

Hey guys,

i have a command which is working like !command #outputchannel url1 url2

"url1" is setting a footer image of an embed and "img2" the thumbnail.
As i sometimes dont wanna use a footer i can remember that i could pass / empty that by just invoke it like this: !command #outputchannel "" url2

Today i used this command since ages and the error tells me that i cant perform it like that.
It would expect a http link instead. So now if i do it like https://"empty".png it work but cant that be done easier?

tribal bough
#

it always works for me in this type of situations

wintry cosmos
#

Yeah its been a while.. not really the best method to perform what i want ( as it is atm ). Ill probably just rewrite it like you said.

#

I thought i could maybe pass it other way without rewrite

coarse spire
#

how can I create a invite link for a certain guild? Here is the code I've got so far;

@commands.has_permissions(administrator=True)
async def servers(ctx):
    embed = discord.Embed()
    for guild in client.guilds:
        embed.add_field(name=":crown:", value=guild)
        link = await guild.create_invite(max_age = 300)
        embed.add_field(name=":crown:", value=link)
    await ctx.respond(embed = embed)```
wintry cosmos
#

I think an invite has to be about a specific channel iirc

#

.rtfm create_invite()

winter condorBOT
#

Target not found, try again and make sure to check your spelling.

coarse spire
#

oh, ok. Cause I'm trying to do so that the bot can generate invite links from server that it is in and not me only

wintry cosmos
#

.rtfm create.invite

winter condorBOT
#

Target not found, try again and make sure to check your spelling.

coarse spire
#

.rtfm create_invite

wintry cosmos
#

yeah you can

#

whats about ctx.channel

#

But there is no channel at all link = await guild.create_invite(max_age = 300)

coarse spire
#

yeah, how can I specify a channel in a server I'm not in then?

#

a random channel

wintry cosmos
#

invitelink = await ctx.channel.create_invite() smth like that

#

and then send(invitelink)

#

Will create an invitelink for the channel the command was invoked

coarse spire
#

if it is ctx though, it creates a invitelink for the channel you use the command in

wintry cosmos
#

Yes, but you dont have to be in that guild. (just the bot) Or am i getting you wrong rn? Thought that you mean other users can use it in channels in other guilds

amber shale
#

does modal support option like slash command?

proud mason
amber shale
#

ok

pallid magnet
#

how to add a reaction emoji after modal?

proud mason
#

.rtfm message.add_reaction

pallid magnet
proud mason
pallid magnet
#

ok🥲

lament crown
#

raise LoginFailure("Improper token has been passed.") from exc
discord.errors.LoginFailure: Improper token has been passed. should i reset my bot tokken bc it is saying this?

rare ice
#

But that means you aren’t using a valid token

night swift
#

bruh the bot keeps restarting ;-; i am running it locally, it might have something to do with how i run it idk

async def main():
    await create_db_pool()
    await bot.start(config.token)
asyncio.run(main())

i use this to run it with asyncpg

lament crown
#

oh ok i will reset the tokken

#

same error after i reset the token

#
import dotenv
import os
dotenv.load_dotenv()
token = str(os.getenv("TOKEN"))
bot.run(token)
#this\/ is in the .inv file
TOKEN = 123456
#this is the error: raise LoginFailure("Improper token has been passed.") from exc
discord.errors.LoginFailure: Improper token has been passed.
#

keep getting the same error after i reset token and paste it in .inv file

rare ice
lament crown
#

it literally just says "None"

rare ice
#

That’s why