#Basic Pycord Help

1 messages Β· Page 7 of 1

shell radish
#

ctx.bot?

rugged lodgeBOT
shell radish
#

yeah

slender cloak
#

ill try it

fleet cedar
#

πŸ‘€

torpid cosmos
#

Hi om

fleet cedar
#

Hello

#

I was accidentally here for a second lul

shell radish
lofty parcel
#

Mood

junior ember
#

How fix

fleet cedar
junior ember
#

aiohttp 3.8.5
aiosignal 1.3.1
async-timeout 4.0.2
attrs 23.1.0
certifi 2023.7.22
charset-normalizer 3.2.0
DateTime 5.2
discord 2.3.2
discord.py 2.3.2
frozenlist 1.4.0
idna 3.4
multidict 6.0.4
pip 23.0.1
py-cord 2.4.1
pytz 2023.3
requests 2.31.0
setuptools 65.5.1
typing_extensions 4.7.1
urllib3 2.0.4
wavelink 2.6.3
wheel 0.41.1
yarl 1.8.2
zope.interface 6.0

#

intents = discord.Intents.default()
AttributeError: module 'discord' has no attribute 'Intents'

junior ember
#

ok done

#

it works now

heavy sky
#

Nice

fleet cedar
#

And then reinstall py-cord

harsh gust
#

is there any trick for using autocompletions for Optional arguments?

slender surge
#

can i have a tasks.loop within a button class?

upper flint
lapis dock
lapis dock
harsh gust
#

I just wanna know if thete is any possible tricks to use autocompletions for optional arguments

#

And yes the arg has to be optional for that command

harsh gust
#

Alr

red pagoda
#

Hello, is it possible to retrive label and value from selected option in select_callback?

rugged lodgeBOT
#

Here's the dropdown example.

lofty parcel
#

@red pagoda

red pagoda
#

Isnt this one only retrieving value?

lapis dock
foggy gull
#

if i get a guild from its id how can i check what roles a user has in that guild (i cant use ctx as its a button inside a dm)

lapis dock
foggy gull
#

?

lapis dock
#

yeah, except you would need to actually pass a user id

foggy gull
#

thanks πŸ™‚

foggy gull
# lapis dock yeah, except you would need to actually pass a user id

and can you help with this: i have a flask server running and i need it so when i go to a url on the flask server (/verified) it send some messages to a user through their dms witht he discord id passed through the url.
This Is What I Have So Far:

@app.route('/verified')
async def verified():
  discordid = request.args.get('discordid')
  robloxuser = request.args.get('robloxusername')
  robloxid = request.args.get('robloxid')
  apiauth = request.args.get('apiauth')
  
  if apiauth == os.environ['API_AUTH']:
    user = await bot.get_user(discordid)
    user.send("test")
  else:
    return "no"

But When I Go To The Url I Get The Error: File "/home/runner/SchoolRpBot/venv/lib/python3.10/site-packages/asgiref/sync.py", line 353, in main_wrap result = await self.awaitable(*args, **kwargs) File "main.py", line 55, in verified user = await bot.get_user(discordid) TypeError: object NoneType can't be used in 'await' expression 172.31.196.1 - - [27/Aug/2023 17:40:52]

little cobalt
#

"NoneType"

foggy gull
little cobalt
lapis dock
#

how is bot defined?

hybrid fossil
#

Hi there!
Does anyone have an idea how to delete this message automatically?

foggy gull
foggy gull
#

if thats what you mea

foggy gull
lapis dock
#

discordid is not None correct?

foggy gull
#

yeah

#

its my discord id

#

i checked by returning it

#

and it returned it fine

lapis dock
#

Somehow your bot is None

foggy gull
daring grove
#

is there a way to fetch the emblem of a role in pycord?

daring grove
#

so like
role: discord.Role
role.icon?

#

like that?

lapis dock
#

πŸ‘

daring grove
#

okay great, tyvm

daring grove
lapis dock
#

Not sure. You will have to try it out

daring grove
#

sure ill try it when i get home

#

thank you

vocal jacinth
#

I see you are currently recommending the unstable branch to get support for new usernames. Is there an "implicitly stable" unstable branch, or is it just unstable and I gotta deal with that?

lapis dock
vocal jacinth
#

thanks

fleet cedar
#

But user.send is. Await that

foggy gull
#

okk

foggy gull
# fleet cedar get_user is not an async function
[2023-08-27 19:25:13,985] ERROR in app: Exception on /verified [GET]
Traceback (most recent call last):
  File "/home/runner/SchoolRpBot/venv/lib/python3.10/site-packages/flask/app.py", line 2190, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/runner/SchoolRpBot/venv/lib/python3.10/site-packages/flask/app.py", line 1486, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/runner/SchoolRpBot/venv/lib/python3.10/site-packages/flask/app.py", line 1484, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/runner/SchoolRpBot/venv/lib/python3.10/site-packages/flask/app.py", line 1469, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
  File "/home/runner/SchoolRpBot/venv/lib/python3.10/site-packages/asgiref/sync.py", line 277, in __call__
    return call_result.result()
  File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/concurrent/futures/_base.py", line 451, in result
    return self.__get_result()
  File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/concurrent/futures/_base.py", line 403, in __get_result
    raise self._exception
  File "/home/runner/SchoolRpBot/venv/lib/python3.10/site-packages/asgiref/sync.py", line 353, in main_wrap
    result = await self.awaitable(*args, **kwargs)
  File "main.py", line 59, in verified
    await user.send(f"Congratulations πŸŽ‰ You Have Verified Your Account: {robloxuser} If You Would Like To Continue With Role Selection Press The Button Below. And If You Are A Vip Member You Can Choose The Role You Want!", view=rolebutton)
TypeError: coroutine.send() takes no keyword arguments
172.31.196.1 - - [27/Aug/2023 19:25:13]```
fleet cedar
foggy gull
torpid stone
#

hi im trying to use cogs ... following the guide and im getting discord.errors.ExtensionFailed: Extension 'cogs.greetings' raised an error: AttributeError: 'Bot' object has no attribute 'add_command'

resource used: https://guide.pycord.dev/popular-topics/cogs

Cogs, often known as modules or extensions, are used to organize commands into groups. This is useful

lofty parcel
#

Show your pip list

torpid stone
#
aiohttp==3.8.5
aiosignal==1.3.1
async-timeout==4.0.3
attrs==23.1.0
certifi==2023.7.22
charset-normalizer==3.2.0
frozenlist==1.4.0
idna==3.4
multidict==6.0.4
py-cord==2.4.1
python-dotenv==1.0.0
requests==2.31.0
urllib3==2.0.4
yarl==1.9.2```
foggy gull
#

wrong error

#
[2023-08-27 19:33:18,242] ERROR in app: Exception on /verified [GET]
Traceback (most recent call last):
  File "/home/runner/SchoolRpBot/venv/lib/python3.10/site-packages/flask/app.py", line 2190, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/runner/SchoolRpBot/venv/lib/python3.10/site-packages/flask/app.py", line 1486, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/runner/SchoolRpBot/venv/lib/python3.10/site-packages/flask/app.py", line 1484, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/runner/SchoolRpBot/venv/lib/python3.10/site-packages/flask/app.py", line 1469, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
  File "/home/runner/SchoolRpBot/venv/lib/python3.10/site-packages/asgiref/sync.py", line 277, in __call__
    return call_result.result()
  File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/concurrent/futures/_base.py", line 451, in result
    return self.__get_result()
  File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/concurrent/futures/_base.py", line 403, in __get_result
    raise self._exception
  File "/home/runner/SchoolRpBot/venv/lib/python3.10/site-packages/asgiref/sync.py", line 353, in main_wrap
    result = await self.awaitable(*args, **kwargs)
  File "main.py", line 59, in verified
    await user.send(f"Congratulations πŸŽ‰ You Have Verified Your Account: {robloxuser} If You Would Like To Continue With Role Selection Press The Button Below. And If You Are A Vip Member You Can Choose The Role You Want!", view=rolebutton)
AttributeError: 'NoneType' object has no attribute 'send'```
lofty parcel
#

If you used get_user then it not in the cache

#

And you have to fetch the user

torpid stone
# lofty parcel Show your code

bot.py

import os # default module
from dotenv import load_dotenv

load_dotenv() # load all the variables from the env file
bot = discord.Bot()

cogs_list = [
    'greetings',
]

for cog in cogs_list:
    bot.load_extension(f'cogs.{cog}')

@bot.event
async def on_ready():
    print(f"{bot.user} is ready and online!")

bot.run(os.getenv('BOT_TOKEN')) # run the bot with the token```

greetings: 

import discord
from discord.ext import commands

class Greetings(commands.Cog): # create a class for our cog that inherits from commands.Cog
# this class is used to create a cog, which is a module that can be added to the bot

def __init__(self, bot): # this is a special method that is called when the cog is loaded
    self.bot = bot

@commands.command() # creates a prefixed command
async def hello(self, ctx): # all methods now must have both self and ctx parameters
    await ctx.send('Hello!')

@discord.slash_command() # we can also add application commands
async def goodbye(self, ctx):
    await ctx.respond('Goodbye!')

@discord.user_command()
async def greet(self, ctx, member: discord.Member):
    await ctx.respond(f'{ctx.author.mention} says hello to {member.mention}!')

@commands.Cog.listener() # we can add event listeners to our cog
async def on_member_join(self, member): # this is called when a member joins the server
# you must enable the proper intents
# to access this event.
# See the Popular-Topics/Intents page for more info
    await member.send('Welcome to the server!')

def setup(bot): # this is called by Pycord to setup the cog
bot.add_cog(Greetings(bot)) # add the cog to the bot```

foggy gull
# lofty parcel And you have to fetch the user

Gives This Error

Traceback (most recent call last):
  File "/home/runner/SchoolRpBot/venv/lib/python3.10/site-packages/flask/app.py", line 2190, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/runner/SchoolRpBot/venv/lib/python3.10/site-packages/flask/app.py", line 1486, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/runner/SchoolRpBot/venv/lib/python3.10/site-packages/flask/app.py", line 1484, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/runner/SchoolRpBot/venv/lib/python3.10/site-packages/flask/app.py", line 1469, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
  File "/home/runner/SchoolRpBot/venv/lib/python3.10/site-packages/asgiref/sync.py", line 277, in __call__
    return call_result.result()
  File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/concurrent/futures/_base.py", line 451, in result
    return self.__get_result()
  File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/concurrent/futures/_base.py", line 403, in __get_result
    raise self._exception
  File "/home/runner/SchoolRpBot/venv/lib/python3.10/site-packages/asgiref/sync.py", line 353, in main_wrap
    result = await self.awaitable(*args, **kwargs)
  File "main.py", line 59, in verified
    await user.send(f"Congratulations πŸŽ‰ You Have Verified Your Account: {robloxuser} If You Would Like To Continue With Role Selection Press The Button Below. And If You Are A Vip Member You Can Choose The Role You Want!", view=rolebutton)
TypeError: coroutine.send() takes no keyword arguments
172.31.196.1 - - [27/Aug/2023 19:25:13]```
fleet cedar
lofty parcel
fleet cedar
foggy gull
#

replit

fleet cedar
#

There should be 1 of bot.run(...) or await bot.start(...) somewhere in your code. Where is that?

foggy gull
#

bot.run(os.getenv('TOKEN'))

little cobalt
fleet cedar
torpid stone
foggy gull
#

on replit

foggy gull
#
import discord
import requests
import asyncio
from flask import Flask
from flask import request
from threading import Thread
import random
import math

verified_role_name = "Kingswood Verified Member"
staff_role_name = "automationCommands"

API_URL_CODES = ""

API_URL_RANKS = ""

app = Flask('')

@app.route('/')
def main():
  return "Bot Online"

def run():
  app.run(host="0.0.0.0", port=8000)

def keep_alive():
  server = Thread(target=run)
  server.start()

bot = discord.Bot()

@bot.event
async def on_ready():
  print(f"{bot.user} is online!")
  keep_alive()

class rolebutton(discord.ui.View): 
    @discord.ui.button(label="Start Role Selection!", style=discord.ButtonStyle.green) 
    async def button_callback(self, button, interaction):
        guild = await bot.get_guild(1143902867317608551)
        user = await guild.get_member(interaction.user.id)
        roles = user.roles
        role = discord.utils.get(guild.roles, name="VIP")
        if role in roles:
          print("48")
        else:
          print("kf")

@app.route('/verified')
async def verified():
  discordid = request.args.get('discordid')
  robloxuser = request.args.get('robloxusername')
  robloxid = request.args.get('robloxid')
  apiauth = request.args.get('apiauth')
  
  if apiauth == os.environ['API_AUTH']:
    user = bot.fetch_user(discordid)
    await user.send(f"Congratulations πŸŽ‰ You Have Verified Your Account: {robloxuser} If You Would Like To Continue With Role Selection Press The Button Below. And If You Are A Vip Member You Can Choose The Role You Want!", view=rolebutton)
  else:
    return "no"

  




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

        self.add_item(discord.ui.InputText(label="Roblox Username"))
        

    async def callback(self, interaction: discord.Interaction):
      digits = [i for i in range(0, 10)]
      random_str = ""

      for i in range(6):
        index = math.floor(random.random() * 10)
        random_str += str(digits[index])
      
      embed = discord.Embed(title="Continue")
      embed.add_field(name="To continue the verification join the game below!", value="https://example.com")
      embed.add_field(name="", value=f"Your Code Is: {random_str}")
      await interaction.response.send_message(embed=embed)
      ApiToken = os.environ['API_AUTH']
      addcodes = f'{API_URL_CODES}/v2/code/add/{random_str}/{self.children[0].value}/{interaction.user.id}/{ApiToken}'
      request = requests.get(url = addcodes)
      
      
        

class MyView(discord.ui.View): 
    @discord.ui.button(label="Verify!", style=discord.ButtonStyle.green) 
    async def button_callback(self, button, interaction):
        RblxUsername = MyModal(title="Verification")
        await interaction.response.send_modal(RblxUsername)
        self.disable_all_items()
        await interaction.message.edit(view=self)

@bot.slash_command(name="verify" ,description="Verify Your Roblox Account!")
async def verify(ctx):
  role = discord.utils.get(ctx.guild.roles, name=verified_role_name)
  if role in ctx.author.roles:
    await ctx.respond("You Dont Have Permission To Use This Command.")
    return
  
  await ctx.respond("We have sent you a dm for further verification", ephemeral=True)
  await ctx.user.send("Click The Button Below To Start The Verification!", view=MyView())


@bot.slash_command(name="setrank" ,description="Verify Your Roblox Account!")
async def setrank(ctx):
  role = discord.utils.get(ctx.guild.roles, name=staff_role_name)
  if not role in ctx.author.roles:
    await ctx.respond("You Dont Have Permission To Use This Command.")
    return
  
  await ctx.respond("We have sent you a dm for further verification", ephemeral=True)
  await ctx.user.send("Click The Button Below To Start The Verification!", view=MyView())

bot.run(os.getenv('TOKEN'))```
lofty parcel
#

Why did you do that

#

I didn't ask you to do that

little cobalt
#

Havent Jack already open a thread?

lofty parcel
#

Yes

torpid stone
# lofty parcel What

aha im new to this so my understanding might be wrong but in my greetings.py i updated my "hello" that has a @command.command abouv it to discord.bot

lofty parcel
#

discord.Bot is the bot instance

fleet cedar
#

Don't use flask with py-cord. Is it not meant to be used async and does weird stuff with the event loop. Use Quart instead. That's an async version of flask

lofty parcel
#

commands.command doesn't work for discord.Bot because it doesn't handle prefixed commands. And that's why it might be erroring

little cobalt
torpid stone
fleet cedar
lofty parcel
#

The bot instance you're using doesn't support prefixed commands.

lofty parcel
#

?tag clients

limber wagonBOT
#

dynoError No tag clients found.

torpid stone
lofty parcel
#

?tag client

limber wagonBOT
#
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
little cobalt
#

yea ok x3

foggy gull
#

so what do i do because i need a apui command i can send a get request to and the bot sends a dm to a user

#

how do i do that then

fleet cedar
#

Swap flask with quart

#

Google how to use quart

#

It should be pretty similar

foggy gull
#

welll it doesnt even work

green kernel
#

If I have a select menu/dropdown in a public channel (that's also tied to a button on the same message/view), are people's selections only visible to them?

shell radish
slender cloak
#

so in my on_application_command_error I have the isinstance for CheckFailure but when that error occurs it doesnt work

    @commands.Cog.listener()
    async def on_application_command_error(self, ctx: discord.ApplicationContext, error: discord.DiscordException):
      if isinstance(error, commands.CheckFailure):
        embed = discord.Embed(title = "Error!" , description = f"There are no mod/admin roles set, or you don't have permission to use this command.", color = discord.Color.light_grey())
        try:
          await ctx.respond(embed=embed, ephemeral = True)
          pass
        except:
          pass
#

it just goes right to my else:

sly quail
#

to add args to the slash command do I just need to add extra args to the function or is it something else

sly quail
#

Thanks

slender cloak
fleet cedar
#

Iirc, Application command errors get wrapped inside a different error or some weird stuff like that

#

.rtfm on_application_command_error

sand salmon
#

class MyView(discord.ui.View):
def init(self):
super().init(timeout=None)

@discord.ui.button(label="⏸️", custom_id="button-1", style=discord.ButtonStyle.primary) # the button has a custom_id set
async def button_callback(self, button, i: discord.Interaction):
    voice = i.guild.voice_client
    await voice.pause()
    await i.response.send_message('βœ… Paused.')

TypeError: object NoneType can't be used in 'await' expression

i looked up on google but everything is for discord.py, any help?

fleet cedar
#

.rtfm VoiceClient.pause

sly karmaBOT
sand salmon
#

oh my god.

#

it was just not using async

#

im dumb

fleet cedar
#

Yea that function isn't async

sand salmon
#

thanks for the help

fleet cedar
#

Np

red pagoda
#

Hello, is there a way how I can retrieve label and value from selected option? I want to return it back to the function. Thanks for the help peepolove

async def select_callback(interaction: discord.Interaction):
    # Get the selected value from the interaction
    selected_value = interaction.data["values"][0]

    return selected_value

options = []
for store, store_id in result.items():
    options.append(SelectOption(label=store, value=store_id))
select = discord.ui.Select(placeholder="Select Store", options=options, max_values=1, min_values=1)
select.callback = select_callback

view = discord.ui.View(timeout=15)
view.add_item(select)
selected_store = await ctx.respond("Please select store", view=view, ephemeral=True)

print(selected_store)
sly karmaBOT
# red pagoda Hello, is there a way how I can retrieve label and value from selected option? I...
# View
class MyView(discord.ui.View):
    def __init__(self, name: str):
        super().__init__()
        self.name = name

    @discord.ui.string_select(...)
    async def button1(self, select: discord.ui.Select, interaction: discord.Interaction):
        await interaction.response.send_message(f"{self.name} chose {select.values[0]}")
        self.stop() # this is the view.stop
#command
@bot.command(...)
async def my_cmd(ctx: discord.ApplicationContext, name: str):
    view = MyView(name)
    await ctx.respond("Please select", view=view)

    # wait till view.stop is called
    await view.wait()

    embed = discord.Embed(description=view.children[0].values[0], ...)
    await ctx.respond(embed=embed)
fleet cedar
#

Just what you need from what I understand

daring grove
#

how do i get the name of a role with it's id?

#

like
role = discord.utils.get(ctx.guild.roles, id=whatever) print(role.name)

daring grove
#

πŸ‘

#

Just having random pycord thoughts while on holiday...

red pagoda
fiery stratus
#

Should I serialize discord Messages and Channels using repr() or using their IDs?

hazy turret
#

Is there any way to disable all prefix commands?
So that I also get no error etc.?
Is there somehow a quick and easy method ?

lapis dock
#

Temporarily or you never want any prefix commands?

hazy turret
little cobalt
hazy turret
# little cobalt use discord.Bot?

Okay if I change bot = commands.Bot to bot = discord.Bot then no prefix commands will be recognized right?
Then I also have to remove the command_prefix or?

lapis dock
#

yes

little cobalt
#

yea

lapis dock
#

Will will also likely have to switch command decorators to
@discord.slash_command

hazy turret
#

Okay everything works thanks! πŸ™‚

deft kestrel
#
@bot.slash_command(description='dasdasd!!!', guild_ids=['x'])
async def suggest(ctx, suggestion):
    embed = discord.Embed(
        title=f"New Suggestion by {ctx.author}",
        description=suggestion,
        color=2829617
    )
    channel = bot.get_channel()
    msg = await channel.send(embed=embed)
    await msg.add_reaction("πŸ‘")

why does it send an application did not respond error but it works?

heavy sky
deft kestrel
heavy sky
lapis dock
deft kestrel
#

one sec

lapis dock
#

can you send your code

deft kestrel
#
@bot.slash_command(description='suggest ton features!', guild_ids=['1144777754894676081'])
async def suggest(ctx, suggestion):
    embed = discord.Embed(
        title=f"New Suggestion by {ctx.author}",
        description=suggestion,
        color=2829617
    )
    channel = bot.get_channel(1145716515006578862)
    msg = await channel.send(embed=embed)
    await ctx.send("Suggestion sent!")
    await msg.add_reaction("πŸ‘")
    await msg.add_reaction("πŸ‘Ž")
heavy sky
#

You have to use ctx.respond not ctx.send to respond to a slash command

deft kestrel
#

alr works now, thanks

heavy sky
#

πŸ‘

lapis dock
deft kestrel
#

alr

deft kestrel
#
@bot.slash_command(description='suggest ton features!', ephemeral=True, guild_ids=['1144777754894676081'])
heavy sky
#

You need to pass it to ctx.respond

deft kestrel
#

oh alr

lapis dock
#

Add it to the respond
await ctx.respond("Suggestion sent!", ephemeral=True)

deft kestrel
#

ok works now

#

ty

red pagoda
hazy turret
#

Is it possible to add a select menu to a view where you can define pre-selected values?
If I have the options [1,2,3,4,5,6], can I say that automatically values from another list should be selected? So for example [2,3,6] ?

shell radish
#

yes

urban zealot
#

Do attachments within slash commands have a size limit. If so, do you know what it is?

round heart
#

What's the best way to reduce the number of "Unknown Message' errors, presumably during a timeout of a View? I don't really have any more info than that lol - I have a simple ephemeral response with a View that is doing disable_on_timeout. I don't remember having so many of these types of errors before.

hazy turret
fleet cedar
#

you could try it and see

lapis dock
daring grove
#

How would I make my bot fetch a list of all roles which have an emblem

lapis dock
round heart
lapis dock
lapis dock
daring grove
#

for role in roles:
if role.emblem:

#

like that?

lapis dock
round heart
# lapis dock I don't think the base View does this

...hm. So what do you do in your own Views? Override on_timeout for everything?
I'm definitely curious why the library isn't doing this, I feel like timing out dismissed interactions would be super common

lapis dock
#

I am planning on overriding on_timeout for most of my views but I have not got around to adding a bunch of error handleing yet.
Bring it up in #discussion or GitHub. You do have a valid point.

hazy turret
lapis dock
#

It is a SelectOption not the select. That only represents one of the options so you could specifiy for many. Then add the list of SelectOptions to the Select

cursive leaf
#

how do i make a task loop at utc 0 every day

lapis dock
deft kestrel
#

back again, how can i have a welcome message?

@bot.event
async def on_member_join(member):
    print(f"new user {member.name}")
    channel = bot.get_channel(1145759009127805039)
    embed = discord.embed(
        title=f"{member.name} has joined the server!",
        color=2829617       
    )
    await channel.send(embed=embed)

this doesn't seem to catch when a member joins the server

lapis dock
#

I think you need the members intent

#

?tag intents

limber wagonBOT
#

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)
cursive leaf
#

mixing relative time and explicit time

#
@tasks.loop(time=time(0,0,0,0,tzinfo=timezone.utc),hours=24)
#

8.08 15:12:06 [Bot] raise TypeError("Cannot mix explicit time with relative time")
28.08 15:12:06 [Bot] TypeError: Cannot mix explicit time with relative time

deft kestrel
# lapis dock I think you need the members intent

that works, but now im getting an attributeerror

  File "", line 26, in on_member_join
    await channel.send(embed=embed)
AttributeError: 'NoneType' object has no attribute 'send'
@bot.event
async def on_member_join(member):
    print(f"new user {member.name}")
    channel = bot.get_channel(1145759009127805039)
    embed = discord.Embed(
        title=f"{member.name} has joined the server!",
        color=2829617       
    )
    embed.set_footer(text="bot by calcium", icon_url='https://calcal.space/favicon.png')
    await channel.send(embed=embed)
little cobalt
deft kestrel
hazy turret
# lapis dock It is a `SelectOption` not the select. That only represents one of the options s...

Okay so I can't implement the following scenario:

I select in my select menu [1,2,3,4,5,6] the options 3,5,6
Then I go to another select menu via a "Next" button. If I now go to "Back" the same select menu comes up with the options [1,2,3,4,5,6]. Can I then here my options, which I have of course saved there already selected for the user, that he can then change these options or must the user click all options again?

deft kestrel
#
intents = discord.Intents()
intents.members = True
intents.presences = True
intents.message_content = True

bot = discord.Bot(intents=intents)
#

no intent errors

little cobalt
#

And also at the Website?

deft kestrel
#

yeah

#

its detecting the user joining

little cobalt
#

Oh

#

Nvm

deft kestrel
#

just the send with my embed

little cobalt
#

You use get_channel

lapis dock
#

?Tag get_x

limber wagonBOT
#

Any function that starts with get_ in Py-cord is retrieving the related object from your bots cache. If the object is not in the bots cache the get_ method will return None. Because of this behavior you should check if the get_x method is None and if it is use the fetch_x method.

Why Is Using fetch_ Without Using get_ First Bad?
The fetch_ method makes a call to the discord API. This API call is unneeded if you already have the information. It will also make your command take longer because it will have to send and than wait for a response from the discord API. It will also contribute to the discord APIs global rate limit of 50 requests per second.

What Is Cache?
The cache is a temporary storage inside your bot. It holds many objects from members to messages. When you restart your bot the cache will be empty. When the cache is full it will delete older objects to make space for the new objects.

deft kestrel
#

ah

cursive leaf
#

@lapis dock

@tasks.loop(time=time(0,0,0,0,tzinfo=timezone.utc),hours=24)

8.08 15:12:06 [Bot] raise TypeError("Cannot mix explicit time with relative time")
28.08 15:12:06 [Bot] TypeError: Cannot mix explicit time with relative time

lapis dock
deft kestrel
#
    if bot.get_channel(1145759009127805039) == None:
        channel = bot.fetch_channel(1145759009127805039)
``` @lapis dock ?
lapis dock
lapis dock
hazy turret
deft kestrel
# lapis dock YEs except you would need to save the get_channel to a varible too

done, new error

TypeError: coroutine.send() takes no keyword arguments
b:\TON\venv\lib\site-packages\discord\client.py:404: RuntimeWarning: coroutine 'Client.fetch_channel' was never awaited
  await self.on_error(event_name, *args, **kwargs)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
@bot.event
async def on_member_join(member):
    print(f"new user {member.name}")
    if bot.get_channel(1145759009127805039) == None:
        channel = bot.fetch_channel(1145759009127805039)
    else:
        channel = bot.get_channel(1145759009127805039)
    embed = discord.Embed(
        title=f"{member.name} has joined the server!",
        color=2829617       
    )
    embed.set_footer(text="bot by calcium", icon_url='https://calcal.space/favicon.png')
    await channel.send(embed=embed)

i cant await it or else that gives me another error

#

hm

#

same thing happens even if i comment it

#

and just straight fetch it

lapis dock
lapis dock
deft kestrel
#

@lapis dock i also get this

  File "b:\TON\main.py", line 21
    await channel = bot.fetch_channel(1145759009127805039)
    ^^^^^^^^^^^^^
SyntaxError: cannot assign to await expression here. Maybe you meant '==' instead of '='?
lapis dock
#

await goes before the function. So in this case before bot.fetch...
I just want to warn you discord bots are advanced. It might benefit you to make sure you understand python basics along with OOP and async before getting to far into the creation of bots

deft kestrel
#

oh wait i see that now

#

omg

deft kestrel
cerulean sun
#

any way to tell chronological order of reacters based on reaction.users() method?

#

like is the .users() method return reacters sorted someway?

daring grove
#

How do i add a repeating thing which pulls all the roles from a server every 5 minutes or so

rugged lodgeBOT
#

Here's the background task example.

lofty parcel
#

reaction.users returns a Member or User object

cerulean sun
lofty parcel
#

its probably how it gets stored by discord

proper dew
#

Hey, where can I find any info about an output like this <function Client.fetch_user at 0x7fc2626c6820>?

torpid cosmos
#

def my_func():
    ...

print(my_func)

This would print

<function my_func at 0x[memaddress]>
#

Generally that's not useful unless you're a serious debugger

proper dew
#

so i need to look under Client.featch_user, in the docs

torpid cosmos
#

yeah, that function is located at discord.Client.fetch_user

#

can i ask what you're doing with that output, though?

proper dew
#

I want to remove a role from a user, but I only have the id from my db

torpid cosmos
#

Can you show us your code, or would you prefer to figure it out on your own?

proper dew
#
    async def on_message(self, message):
        """
        Select user and his story role state, which has the most shark_story_points
        check if he has the story role -> if yes return
        if not get the user_id from the user, who has the story role
        take the role away from the old user and give it to the new
        """
        async with aiosqlite.connect("level.db") as db:
            #select user, storyRole
            async with db.execute("SELECT user_id, StoryRole FROM users WHERE max(shark_story_points)") as cursor:
                result= await cursor.fetchone()
                if result is None:
                    return
                user_id, StoryRole = result #save infos
            if StoryRole==True:
                return
            #get old user with currently the role
            async with db.execute("SELECT user_id FROM users WHERE StoryRole=True") as cursor2:
                result2 =await cursor2.fetchone()
                guild= discord.Bot.featch_guild
                print(guild)

do not pay attention to spelling in the comments, thanks

torpid cosmos
#

That's fine. Do you mind editing it to be in a code block?

little cobalt
#

?tag codeblock

limber wagonBOT
#

Please put your code in a code block:
```py
Here is your Code
```

That makes reading code in Discord a lot easier:

print("This is an example.")
distant hazel
#

hey is there anyone experienced with the voice receiving here?

#

im trying to add support for it to a discord bot client in another language but im having issues with the decoding part

#

when i do the echoing all my bot does is beatbox

torpid cosmos
proper dew
#
  print(guild)```
torpid cosmos
#

That isn't the code you are using. Can you please show us your whole code at the moment, including what is printing the aforementioned output?

proper dew
torpid cosmos
#

I see. It looks like in your code you are printing the fetch_guild function (which you have spelled wrong, by the way). In the output you gave us, it claims that you are printing fetch_user somewhere.

#

In any case, to get a guild, you would want to actually call the function and pass the user's ID into it.

#
my_guild_id = 0123456789
guild = bot.fetch_guild(my_guild_id)```
#

It would also be smart to try to use your own discord.Bot or discord.Client instance instead of using it straight from the library.

torpid cosmos
#

And what exactly do you mean by beatboxing?

distant hazel
#

cut off audio

#

here:

daring grove
#
@tasks.loop(seconds=1)
async def my_background_task(self):
    channel = self.get_channel(1143710797189623848)
    await channel.send("Hello")

bot.run(token)

would this work?

torpid cosmos
#

No. You would almost definitely get ratelimited.

distant hazel
daring grove
torpid cosmos
#

that doesnt look like python

distant hazel
#

at the end is where the magic happens

torpid cosmos
distant hazel
#

yeah like i said in another language

distant hazel
torpid cosmos
#

I'm confused. What's the project structure looking like here? What is that lua supposed to be doing?

#

Does the Lua code get microphone input and pass it to your Pycord bot?

distant hazel
#

it uhm kinda has nothing to do with pycord other than pycord has support for voice receiving

torpid cosmos
distant hazel
#

okay ill see

shell radish
#

you can always check the source code tbh

distant hazel
#

thats what im trying to decipher right now

torpid cosmos
#

It's simply
your_function.start()

daring grove
#

and this should be at the end right?

torpid cosmos
#

Do that once your bot is already running, though. Preferably in an on_ready or similar function

daring grove
#

okay sure

torpid cosmos
#

Here's an example from our amazing Pycord guide

import discord
from discord.ext import tasks

bot = discord.Bot()

@bot.event
async def on_ready():
    very_useful_task.start()

@tasks.loop(seconds=5)
async def very_useful_task():
    print('doing very useful stuff.')

bot.run("TOKEN")```
shell radish
torpid cosmos
daring grove
#

oop

#

I got it working

#
@tasks.loop(seconds=10)
async def rolefetch(self):
    channel = self.get_channel(1143710797189623848)
    await channel.send("Hello")

@bot.event
async def on_ready():
    print(f"Logged into discord api as: {bot.user}!")
    rolefetch.start(bot)
#

okay its annoying me now

torpid cosmos
#

Rad. You didn't need to pass in self though unless your bot is in a class.

#

In that case you wouldn't pass bot when calling it either

daring grove
#

I just have, bot = discord.Bot()

torpid cosmos
#
async def rolefetch(self):
    rolefetch.start(bot)
#

you don't need self or bot in these lines respectively

#

unless the code is in a class, in which case you wouldn't need to pass bot

daring grove
#

how would I do self.get_channel?

torpid cosmos
#

You wouldn't. You'd use your bot object. bot.get_channel

daring grove
#

smart

#

could i do bot.send instead?

#

or

torpid cosmos
#

no, you'd still need to do channel.send because you are calling the send method of channel

daring grove
#

πŸ‘

#

thank you

daring grove
torpid cosmos
#

You'd use the Guild.roles property

#

You can fetch a guild by ID by using the Bot.fetch_guild or Bot.get_guild methods

daring grove
#

ahh

#

I see

torpid cosmos
#

It's recommended to use get_guild though

rare condor
#

how do you make a dedicated error handler for a single command?

#

like is there a decorator for it?

shell radish
#

if your command name is stupid, then use @stupid.error

rare condor
#

it was annoying me cuz I was getting errors from that

#

but i forgor to place

#

the error parameter

round heart
#

"@stupid.error" definitely decorates all my mistakes

slender surge
#

does anyone know why, when i start a tasks.looop in another loop, then close that loop, why doesn’t it start the other loop. ive tested everything and it just doesn’t start

daring grove
#

Is there a good way to get sort of a 'main' colour of someone's pfp and set it to be the embed colour

lofty parcel
#

You'd need some image library

daring valve
# daring grove Is there a good way to get sort of a 'main' colour of someone's pfp and set it t...
cache = LRUCache(512)


@cached(cache=cache)
async def dominant_color(link: str):
    try:
        async with aiohttp.ClientSession() as session:
            async with session.get(link) as resp:
                if resp.status == 200:
                    color_thief = colorthief.ColorThief(BytesIO(await resp.content.read()))
                    x = int(
                        "".join(f"{i:02X}" for i in color_thief.get_color(quality=250)), 16
                    )  # rgb tuple to hex to dec
                    if not x:
                        return 460551
                    return x
    # if any unexplainable shit happens...
    except Exception as e:
        print(e)
        return 460551
#

You need to install colorthief, aiohttp and cachetools packages

#

change quality to change quality:
Bigger number = faster, but worse quality
(uses every 250th pixel for dominant)
In my experience 250 is enough

daring grove
#

or

daring valve
#

Embed(colour=await dominant_color(user.display_avatar.url))

daring grove
#

alright

#

what does return 460551 do?

#

whats so specific to 460551

daring valve
#

Oh wait, no

#

You can use Color.embed_background()

#

Tbh I forgot why I use exactly this color

#

Β―_(ツ)_/Β―

#

Funny number I guess

daring grove
daring valve
#
import aiohttp
import colorthief
from asyncache import cached
from cachetools import LRUCache
from io import BytesIO
daring grove
#

thanks

daring grove
daring valve
daring grove
#
Traceback (most recent call last):
  File "C:\PYTHON310\lib\site-packages\discord\bot.py", line 1133, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\PYTHON310\lib\site-packages\discord\commands\core.py", line 381, in invoke
    await injected(ctx)
  File "C:\PYTHON310\lib\site-packages\discord\commands\core.py", line 139, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: Constructor parameter should be str
#

line 121, in unlockedroles unlocked_roles_embed=discord.Embed(title=f"Unlocked roles for {ctx.author.global_name}", colour=await dominant_color(ctx.author.display_avatar))

lofty parcel
#

shouldnt it be display_avatar.url

daring grove
daring grove
#

Ah

daring valve
#

Sorry, I used my internal user class πŸ’€

daring grove
#
@tasks.loop(seconds=10)
async def rolefetch():
    server = bot.get_guild(1079543491048263720)
    for role in server.roles:
        serverroles.clear()
        serverroles.append(role)

why is this only outputting

[<Role id=1145856924051583006 name='Role Selector'>]
#

I was expecting it to output a list of all the roles in the guild

daring valve
#

Do you have intents + permissions?

#

If yes, try to fetch guild

daring grove
#
    for role in server.roles:
AttributeError: 'coroutine' object has no attribute 'roles'
#

hm

#

I tried switching it to fetch_guild

daring valve
#

await fetch bruh

daring grove
#

same thing

#

maybe because its at the top of all the roles?

daring valve
daring grove
#

I do

#

wait

#

permissions yes

#

Intents im not sure

#

I didnt declare them anywhere

daring valve
daring valve
#
  • I think you can just serverroles = server.roles
daring grove
#

is server.roles already a list?

daring valve
#

yes lol

daring grove
#

I feel very silly now

#

Thanks for that

junior ember
#

is it possible to make

async def record(ctx):  # If you're using commands.Bot, this will also work.
    voice = ctx.author.voice

    if not voice:
        await ctx.respond("You aren't in a voice channel!")

    vc = await voice.channel.connect()  # Connect to the voice channel the author is in.
    connections.update({ctx.guild.id: vc})  # Updating the cache with the guild and channel.

    vc.start_recording(
        discord.sinks.WaveSink(),  # The sink type to use.
        once_done,  # What to do once done.
        ctx.channel  # The channel to disconnect from.
    )
    await ctx.respond("Started recording!")```
to only captuire 1 person's voice?
#

stolen from docs btw

daring grove
#

Is there a way to add this icon at the end of a value of a field in an embed?

#

I tried and it just did this

#

Is it possible?

daring valve
#

use emoji?

#

upload custom emoji and use it

daring grove
#

Do I need any more permissions to add a role?

#

The bots role is above the role I want to add

little cobalt
#

And what are the bot permissions?

daring grove
little cobalt
#

At the Server

daring grove
little cobalt
#

mhm

#

What are the bot intents?

daring grove
#

do I need to?

little cobalt
#

Do you try it with an interaction or where do you do it?

daring grove
#

just a slash command

little cobalt
#

do you do it with ctx.author.add_roles? or how

#

for a slash command you dont need intents

rapid jackal
#

guild.members is returning a list of members right?

little cobalt
rapid jackal
little cobalt
#

Yes it does

rapid jackal
sour musk
#

Heya, I have a question... stupid question...
After a long break, I started improving the bot and decided to make a simple embed generator for future text designs
But I have a problem with creating exceptions if one of the many items is removedBut I have a problem with creating exceptions if one of the many items is removed. Example on screenshot

#

I had an idea to exclude reading individual lines of code, but I just can’t imagine how to do it more accurately ... in general, the idea was to enumerate embed variations through if, elif

daring valve
#

uhm, what?

#

I'm not sure, but making embed generator with slash commands is not the best idea imo

little cobalt
#

What?

daring valve
#

Because slash commands has options limit of 25

little cobalt
#

Same for embed fields

daring valve
little cobalt
#

Yea

daring valve
#
  • author, title, description, footer and so on
sour musk
sour musk
daring valve
sour musk
#

I did not go deep into this thing and in my opinion it has problems with forwarding

daring valve
#

You can try something like that

#

#creations message

daring valve
#

Do you use a translator?

sour musk
#

while working with discord forms, I came across that sending to another channel needs more shamanism than I would like, especially when I didn’t delve into it and there are restrictions up to 4 points

sour musk
#

I tried to do it in English for input, but it turns out 4 times worsedoggokek

daring valve
sour musk
#

Okie

unkempt cipher
#

L

daring valve
#

lala moment

daring grove
#
@bot.slash_command()
@discord.option("role", description="Role you would like to display.", type=discord.Role, required=True)
async def setrole(ctx, role: discord.Role):
    author_id = ctx.author.id
    author_roles = []
    author_record = session.query(UserRoles).filter_by(user_id=author_id).first()
    author_unlocked_roles = json.loads(author_record.unlocked_roles)
    role_id = role.id
    set_role = discord.utils.get(ctx.guild.roles, id=role_id)

    if not author_record:
        await ctx.respond("You do not have any unlocked roles", ephemeral=True)
        return
    else:
        if role_id not in author_unlocked_roles:
            await ctx.respond("You do not have this role unlocked.", ephemeral=True)
            return
        else:
            if set_role in ctx.author.roles:
                await ctx.respond("You already have this role selected", ephemeral=True)
                return
            else:
                emblem_role_present = False

                for role1 in ctx.author.roles:
                    if role1.icon:
                        await ctx.author.remove_roles(role1)
                        await ctx.author.add_roles(role)
                        emblem_role_present = True
                        break

                if emblem_role_present:
                    await ctx.respond(f"Successfully set display role to {role.name}.", ephemeral=True)
                else:
                    await ctx.author.add_roles(role)
                    await ctx.respond(f"Successfully set display role to {role.name}.", ephemeral=True)

I have a command which I would hope adds the role specified in the command and removes any roles with icons from the user
however after 2 uses of the command working fine, it seems to just add the role and not remove the role with the icon

#

doing /setrole beans works
then doing /setrole noodles work
but if i do /setrole beans it will not remove the role 'noodles' just add the role beans

#

assuming both beans and noodles have emblems

fleet cedar
#

you are currently doing it inside the for loop

daring grove
#

Yeah

#

How would I do that?

daring grove
#

The list was empty

fleet cedar
#

oh wait. you break the for loop

#

then ratelimit shouldnt be an issue imo

#

sorry

daring grove
fleet cedar
#

hmm

daring grove
#

then on the third try

#

the list was empty

fleet cedar
#

oh interesting

#

maybe the user doesnt have any such roles remaining?

daring grove
#

i would do

#

/setrole noodles
/setrole beans
and this would work fine

#

it would give me the role noodles

#

then when i did /setrole beans it would remove the noodles role and give me role beans

#

but when i did /setrole noodles again
it would just not remove the role beans give me role noodles

#

so id have both roles

#

i cant really think of any reason why this may be

daring grove
#

im clueless to be honest...

fleet cedar
#

you could enable logging and see if it is actually a ratelimit issue

#

.logging

sly karmaBOT
daring grove
#

Im not sure how to tell 100% if it is

#

But i feel like it is

#

How would I fix this?

fleet cedar
daring grove
#
logger = logging.getLogger('discord')
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)
#

I just did this

#

There any way to simplify it?

daring grove
daring grove
#

it's not a ratelimit

lofty parcel
daring grove
#

Ive been spending so long I can't see anything that it may be

lofty parcel
#

Dunno, didn't read your issue

daring grove
#

Thought when the command is ran the 3rd time it doesn't remove the role with the emblem it just adds the specified one

vivid patio
#

i have an on_ready listener in my cog and its not activating when the cog is reloaded, is there a better listener that activates when the cog is loaded?

vivid patio
daring grove
#

For some reason, this role isnt being fetched when i do

    server = await bot.fetch_guild(669623322496991256)
    global server_roles
    server_roles.clear()
    for server_role in server.roles:
        if server_role.icon:
            role_names = [r.name for r in server_roles]
            if server_role.name not in role_names:
                server_roles.append(server_role)
        else:
            continue
    print(server_roles)

Is there ar eason for this?

#

The role does have an icon i hope

shell radish
#

what does server.roles return? an empty array?

daring grove
shell radish
#

what I said

daring grove
#

however i want only the roles with icons

shell radish
#

try using bot.get_guild

daring grove
#
    server = bot.get_guild(669623322496991256)
    global server_roles
    server_roles.clear()
    for server_role in server.roles:
        if server_role.icon:
            role_names = [r.name for r in server_roles]
            if server_role.name not in role_names:
                server_roles.append(server_role)
        else:
            continue
    print(server_roles)
#

doing this returns the same list as before

#

doesnt include supporter in it

shell radish
#

could you output or debug the value on each iteration of server_role

daring grove
# shell radish could you output or debug the value on each iteration of `server_role`

if this is what you're asking
[<Role id=1131329873370169425 name='Steam Verified'>, <Role id=1131727548091473921 name='Artist'>, <Role id=807953154846883871 name='EUSL Veteran'>, <Role id=1142180496151945256 name='S8 Challenger Winner'>, <Role id=1141868274129326162 name='S8 Bronze'>, <Role id=1141867620786782268 name='S8 Silver'>, <Role id=1141866170845249597 name='S8 Gold'>]
this is what server_roles prints as

shell radish
#

server_role not server_roles

daring grove
#

oh oops

#
Steam Verified
Artist
EUSL Veteran
S8 Challenger Winner
S8 Bronze
S8 Silver
S8 Gold
#

each iteration

shell radish
#

so the role isn't even there

daring grove
#

no, i have no idea why

#

it has an icon

#

but apparently it doesnt

daring grove
shell radish
#

Β―_(ツ)_/Β―

daring grove
#

sucks

round heart
#

In a ApplicationCommandInvokeError, is there a good/known way to see the request was so that I can work out what data.components.1.componenets.0.options.0.value refers to?

shell radish
round heart
#

Well I don't even know what the sent structure is, so I can't count.

shell radish
#

the 1 means row 1

#

the 0 means item 0

#

the option means option 0

#

value means value

round heart
#

Turns out I'm dumb.

I do wish it was easier to see raw payloads to Discord, though.

grim estuary
#

Hello! How can I replace the help command with my own?

daring valve
deft kestrel
#

getting a no module named discord error

lofty parcel
#

Did you install the library? bruh

grim estuary
lofty parcel
deft kestrel
lofty parcel
deft kestrel
#

its on a server

atomic mortar
#

is the pycord library on replit

heavy sky
daring grove
#

Is there a way to limit this list of roles to only certain ones i want to show?

lofty parcel
#

youd need to use an autocomplete and parse it by yourself

daring grove
#

damn

atomic mortar
heavy sky
#

?tag replit

limber wagonBOT
heavy sky
#

@atomic mortar ^

atomic mortar
#

alright

#

only use replit as a last resort

#

πŸ’€

heavy sky
#

yep, replit isn't good for hosting bots

#

?tag norepl

limber wagonBOT
#

Why NOT to use Repl as a hosting platform

You should not use Repl.it to host your bot.
It may be a nice option as its "free" but you should use something else considering the major flaws.

  • The machines are super underpowered.
    This means your bot will lag a lot as it gets bigger.
  • You'll need a web server alongside your bot to prevent it from being shut off.
    This isn't a trivial task, and eats more of the machines power.
  • Repl.it uses an ephemeral file system.
    This means any file you saved via your bot will be overwritten when you next launch.

IMPORTANT

  • They use a shared IP for everything running on the service.
    This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.

Please avoid using repl.it to host your bot. It's not worth the trouble.

If you're looking for free options, consider using AWS/Google Cloud Platform/Azure and its respective free tiers or just pay for a vps.

stray cape
#

hey guys where did bot.slash_command go?

#

no aswer?

heavy sky
#

.rtfm discord.Bot.slash_command

stray cape
#

so my autocompletion is

#

lying

#

thats possible

#

it is just this

lofty parcel
#

You should ask in the wavelink server

#

It's not a pycord issue

#

Google is free

daring grove
red mist
#

You read trough the Wavelink docs.

#

Google : "Python Wavelink docs"

median sundial
#

Is there any other way to detect if the bot is mentioned in a text message other than checking every new message for mentions?

shell radish
#

you can poll the channel history, but that's basically the same thing

hazy turret
#

What can be the reason that a tasks.loop of my bot does not work after a few days?
Could it be that there are problems with the Discord API and there is somehow a contact break or something?
Because if I restart the bot then it works again for a few days. But there is no interval after which it always stops working.
Is there a solution for this or how can I do the whole thing best does anyone have an idea?

median sundial
shell radish
#

you just check it in on_message

median sundial
#

Alright thanks

red mist
#

🧠

Person A : Asks for an answer on Topic D
Person B : Gives them a book on Topic D
Person A : refuses to read it

#

Whats wrong with the docs?

#

You dont know how to use them or...?

median sundial
#

Docs are good if you have a basic understanding of how to use a package/library

red mist
#

I mean ig you can ask for support, but I am not a wavelink dev and I dont know if theres a discord server ab it.

So in my eyes all you'd be stuck with at this point are the docs.

#

Literally this took me less than a fucking minute, and you are telling me google is not giving you anything?

ITS ON THEIR GOD DAMN GITHUB PAGE!

red mist
#

Im sorry but wtfff

foggy ocean
#

hi, is there a way of me being able to grab all the message logs data between me and a person

#

i wanna do some processing on that data for fun

#

i feel like its prolly not allowed tho

red mist
#

Well first of all, yes it is possible (if you are talking about using a bot to grab this data on a server)

It is allowed for moderation purposes, but I recommend telling the person you're doing it with that you're doing it.

#

You can either store all of the messages in a database such as mongodb or sqlite

technically any text file would suffice but thats up to you;

I just know from experience that you should use the on_message event to basically handle all messages sent in a discord server (which the bot can read! So you need to make sure the bot has the intents to do so)

And then just dump them into either your database or a text like file ig.

#

any file would do tbf

hazy turret
#

What can be the reason that a tasks.loop of my bot does not work after a few days?
Could it be that there are problems with the Discord API and there is somehow a contact break or something?
Because if I restart the bot then it works again for a few days. But there is no interval after which it always stops working.
Is there a solution for this or how can I do the whole thing best does anyone have an idea?

red mist
hazy turret
red mist
#

Also

#

You can use the logging package from python to check what your bot is doing

hazy turret
red mist
#

I used to have something like this in my main.py file (I literally copy pasted so I cannot guarantee you it'll work, you may need to change some adjustments.)

logger = logging.getLogger('discord')
logger.setLevel(logging.DEBUG) # CRITICAL ERROR WARNING INFO DEBUG # Use any of those ig.
handler = logging.FileHandler(filename='log/latest.log', encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)

with open('log/latest-console.log', 'w'):
    pass
logging.basicConfig(filename='log/latest-console.log', level=logging.DEBUG, format='%(asctime)s:%(levelname)s:%(name)s: %(message)s', encoding='utf-8')
red mist
#

also make sure to make a log file for it, or have your code create one, because now its just going from root dir to log to latest-console.log file

hazy turret
red mist
#

Idk I genuinely dont know, which is why I used to do this log file thingy. Worked great for me

red mist
#

youll see when you understand the code xd

hazy turret
#

I have implemented a logger. Will run the bot again and see what comes around Thanks! πŸ™‚

red mist
#

Nice :)

red mist
little cobalt
#

So....

#

I cannot see any of my slash commands anymore

#

with my main account I can see them but not with my alt

red mist
#

guild slash command permissions?

#

could be admin commands or dev commands won't be shown

#

Dunno

little cobalt
#

0 permissions

#

basic slash commands

red mist
#

uhm the what, either your main is blacklisted, or your alt is whitelisted by your bot dunno

fickle salmon
graceful cove
#

is there a documentation with all the features of pycord listed? if so where can i find it?

little cobalt
#

Its working at the test server

#

so weird

red mist
#

Synched only to a guild?

little cobalt
#

no they are global

red mist
#

the fk

little cobalt
#

yea...

red mist
#

r u sure?

#

100%

#

Did you test it?

little cobalt
#

yea

red mist
#

What

fickle salmon
red mist
#

does your main acc have any roles in the server?

#

which possibly

#

could make it so

#

that your alt acc

#

isnt able to see commands

red mist
little cobalt
#

I saw that one x3

#

I still have to learn how to use customtkinter

red mist
red mist
#

only for that one scenaria

little cobalt
#

I still want to create something for the OpenDTU project

graceful cove
#

bot does not want to connect (will upload image)

#

need help to correct this error

little cobalt
#

read the error

graceful cove
#

im dumb

#

i dont understand the error

#

python syntax errors are a pain to understand

#

im not at that level yet

little cobalt
#

python is really easy

graceful cove
#

oh yea

#

im dumb

#

yea

graceful cove
#

fixed it

fickle salmon
grizzled loom
#

is there a limit, how many embeds can be given to paginator at once?

shell radish
grizzled loom
fickle salmon
shell radish
fickle salmon
#

I thought it was 5 embeds per message

#

25 seems like a ton

shell radish
#

oops, it seems like 10

grizzled loom
# shell radish oops, it seems like 10

Maybe i stated my question poorly. I meant if i create a bundle of (working) messages, that respect char and field limits and all that, package them in a list and hand this list over to paginator

#

then the limit of those messages is 10?

#

(it can have in a menu)

shell radish
#

the only limit is your system's memory

grizzled loom
#

damn. then my error must be somewhere else. Thanks!

shell radish
#

you should probably just send the error

grizzled loom
#

I will, next time it shows up.

lapis condor
#

I am having trouble sending an embed.

footer = str("Made by EJ Studios")

            Info_embed = discord.Embed(
                colour=discord.Colour.green(),
                title="name",
                description="name")
            Info_embed.set_author(name="Info")
            Info_embed.add_field(name="Info", inline=True)

            Info_embed.add_field(name="Name", value="Info", inline=False)

            Info_embed.set_footer(text="Made by EJ Studios")

            await user.send(embed = Info_embed)```

If i do  ```await user.send(".",embed = Info_embed)``` it will send a . but no embed and if i dont i get an "cant send empty messages error".
little cobalt
lapis condor
#

No, this is a role command, when someone clicks on a reaction they get a role and this embed should be send to them.

tepid coyote
#

Is there a max number of options a slash command can have?

shell radish
#

25

#

including sub groups etc.

deft kestrel
#

I am having an issue with 'on_guild_channel_create' and getting the following error:
AttributeError: 'dict' object has no attribute 'guild'

I am trying to get a specific channel by getting all the channels in the guild like so:
logChannel = discord.utils.get(channel.guild.channels, id=channel_id)

I am using this method everywhere else like, on_guild_channel_update etc without issues.

junior ember
#

anyone know how to bypass discord.errors.HTTPException: 413 Payload Too Large (error code: 40005): Request entity too large

drifting turtle
#

sounds like more like your code has issues than anything else

fickle salmon
junior ember
#

what mean

safe nest
#

it means make the message shorter

junior ember
#

its a file tho

edgy nest
#

the size limit is supposedly 25 MiB for the entire request

cerulean sable
#
if hasattr(interaction, 'original_message'):
    try:
        await interaction.original_message.edit(embed=embed, view=self)
    except discord.errors.HTTPException as e:
        print(f"An error occurred while editing the message: {e}")
else:
    try:
        await interaction.response.send_message(embed=embed, view=self)
    except discord.errors.HTTPException as e:
        print(f"An error occurred while sending the message: {e}")

This code causes an error every time, it says that the interaction has been already acknowledged, but nowhere in my code have I added a ".send_message" or ".edit".

#

Why is it so?

rapid jackal
#

is @fleet cedar 's pull request for the paginator still open? bec. I can't find the PR

lofty parcel
#

Stop crossposting

#

It's just annoying

fleet cedar
#

What was the topic?

#

I have made multiple prs for paginator lul

rapid jackal
fleet cedar
#

It's there on the dev release

#

See #library-updates

rapid jackal
#

Ok thanks

strange hamlet
#

what am I missing in my script?

lofty parcel
#

And you just leaked your token

#

Congrats

strange hamlet
#

it is already got resseted

#

what do you mean by intents?

lofty parcel
#

?tag intents

limber wagonBOT
#

Pycord Docs - Intents
Discord API Docs - 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)
strange hamlet
#

I get this error

lofty parcel
#

It is intents.messages

strange hamlet
#

ok

#

now I get this

#

maybe I should change the name of the variable

lofty parcel
#

I don't know what you're doing without seeing code

strange hamlet
#
from discord.ext import commands

intent = discord.Intents.all()

bot = commands.bot(prefix="!", intents=intent)

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name}')

@bot.command()
async def hello(ctx):
    await ctx.send('Hi')


@bot.command()
async def shutdown(ctx):
    await ctx.send('Shutting down...')
    await bot.close()

bot.run('TOKEN')
#

any ideas?

lofty parcel
#

Whats your pycord version

strange hamlet
#

1.7.3

little cobalt
#

check out #library-updates

strange hamlet
little cobalt
lofty parcel
#

That's pycord

strange hamlet
lofty parcel
#

The library name is py-cord

#

Pycord is another library not related to Discord

strange hamlet
#

oops - I installed something called pycord

lofty parcel
#

You're probably using dpy or something

strange hamlet
#

alright

#

I've installed it

#

the 2.5.0

lofty parcel
strange hamlet
#

no

#

should I?

#

I have this

#

anf this

lofty parcel
#

Uninstall dpy

#

And uninstall py-cord

strange hamlet
#

done

lofty parcel
#

And re install py-cord-dev

strange hamlet
#

that's what I got now

#

and no discord.pu

#

py

lofty parcel
#

You should be good to go

strange hamlet
#

I get an error when I run this code now:

#
from discord.ext import commands

# Create an Intents object with all intents
intents = discord.Intents.all()

# Create a bot instance with the specified intents
bot = commands.Bot(command_prefix='!', intents=intents)

# Event handler for when the bot is ready
@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name}')

# Command to respond to !hello
@bot.command()
async def hello(ctx):
    await ctx.send('Hello!')

# Run the bot with your token
bot.run('/')
strange hamlet
#
import discord
from discord.ext import commands

intents = discord.Intents.all()
intents.messages = True

client = commands.Bot(command_prefix='!', intents=intents)

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

@client.command()
async def foo(ctx, arg):
    await ctx.send(arg)
    print("Working")

client.run('MTE0Njc4MzQ4OTU5Nzg5ODgyNA.GlJJBe.egOxTgXTAoOmg0pjp88XxWtWL-J3Xp4LBI50uo')
#

for this code

heavy sky
#

read the error

#

it says what you need to do in it

#

"Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead."

strange hamlet
#

yes

#

it has administrator

heavy sky
#

That's not what the error asks for. You need to go to the developer portal and enable privileged intents

strange hamlet
#

yes I did

#

thanks

heavy sky
#

it works now?

little cobalt
strange hamlet
#

already did

vital bramble
#

how can I change the nickname of a member?
I can't seem to find it...

#

oh got it xD
member.edit

heavy sky
#

yep lol

dusky ermine
#

How do you supply an announcement channel as the type for the @option decorator?

@option("channel", TextChannel | Thread, description="...")
heavy sky
dusky ermine
heavy sky
dusky ermine
#

It doesn't seem to have any effect

heavy sky
#

can you show your code?

dusky ermine
#
@slash_command(
        name="follow",
        description="Follow a Threads feed in a channel",
    )
    @guild_only()
    @cooldown(1, 5, BucketType.user)
    @default_permissions(manage_channels=True)
    @option("username", description="The username of the user to follow")
    @option("channel", TextChannel | Thread, description="The channel to post new threads in")
    @option("role", Role, description="The role to ping when a new thread is posted", default=None)
    @option("send_reposts", bool, description="Whether to send reposts of threads that have already been posted", default=True)
    @option("send_replies", bool, description="Whether to send the account's replies to threads. Premium only", default=False)

This is in a Cog

heavy sky
#

And you want channel to take an announcement channel?

dusky ermine
#

So I've tried adding ChannelType.news to TextChannel | Thread and also tried adding it into the list for the channel_types kwarg

heavy sky
#

Modify it to look like this:

@option("channel", channel_types=[discord.ChannelType.news], description="The channel to post new threads in")

#

and make sure that the channel argument in the async def takes a discord.TextChannel

#

otherwise it won't work

dusky ermine
#

It still doesn't work

#

The news channel doesn't show up in Discord as an option for the param

heavy sky
#

hmm, weird, that worked for me

dusky ermine
#

Could you pls send ur code

heavy sky
#

I didn't try in a cog though, but this worked for me:

@bot.command()
@option("channel", channel_types=[discord.ChannelType.news], description="...")
async def command(ctx, channel:discord.TextChannel):
    await ctx.respond(channel)```
#

only news channels showed up in the option

dusky ermine
#

Strange, it shows all channels for me when I do it

#

What version of Pycord are you on?

heavy sky
#

hm, weird...

#

I'm on 2.4.1

dusky ermine
#

Alright, lemme try updating and see if that fixes it

heavy sky
#

okay

#

Imma try it in a cog as well, and see if that makes any difference

dusky ermine
#

It works outside of cogs, but not inside

heavy sky
#

hmm

#

one sec

dusky ermine
#

@heavy sky updating to py-cord-dev==2.5.0rc5 fixed it

#

It works in cogs too

heavy sky
#

oh, nice

dusky ermine
#

Thanks for your help

heavy sky
#

No problem πŸ˜„

little cobalt
heavy sky
#

Seems to be working fine in cogs on 2.4.1 for me though...

deft kestrel
vocal wagon
#

Hi.. so I am pretty new to pycord
Like I have been using discord for some time and I have seen this dissapearing scoreboards , that is only visible to the person who invoked it
I am trying to do that.. idk the name foe such a component.. can someone redirect me to the right resource?

safe nest
#

I think the reply example displays an ephemeral reply iirc

rugged lodgeBOT
#

Here's the reply example.

safe nest
#

Oh, not that one

round heart
#

Uh, what am I doing wrong here -- if I send ApplicationContext.respond(..., view=None) I get an error that NoneType doesn't have a timeout. But None is a default value for view in the underlying methods? Is this a bug in ApplicationContext?

shell radish
#

you're not sending anything?

edgy nest
#

i think the default might be MISSING

round heart
#

discord.interactions.send_message() has view as a default of None. But I suppose it's possible it's not using that method

edgy nest
#

respond's param defaults are inconsistent

#

because it depends on whether or not the interaction was responded to

#

for followup.send the default is MISSING

#

i have no clue why

shell radish
#

there's probably a good reason for it

edgy nest
#

other than send and edit using the same handle_params function

#

which we can probably fix in 3 minutes

hazy turret
#

Why do my prefix commands suddenly stop working?
Is there a general bug with Discord at the moment?

little cobalt
#

why did you also add content=?

shell radish
#

?

little cobalt
#

for text but not an embed

shell radish
#

where

#

do you know how kwargs work

hazy turret
#

Does anyone have any idea why all of my bots suddenly stopped working without me changing anything?
Slashcommands still work without problems

shell radish
hazy turret
# shell radish do you have message content intents

In the developer portal I have MESSAGE CONTENT INTENT enabled and in my bot:

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


status = discord.Status.online
activity = discord.Activity(type=discord.ActivityType.watching, name="Status")

bot = commands.Bot(
    command_prefix=PREFIX,
    intents=intents,
    debug_guilds=None,
    status=status,
    activity=activity,
    help_command=None,
)```
shell radish
hazy turret
shell radish
#

error with traceback?

#

?tag codeblock

limber wagonBOT
#

Please put your code in a code block:
```py
Here is your Code
```

That makes reading code in Discord a lot easier:

print("This is an example.")
shell radish
#

what are you using to run your bot

#

that makes sense.

#

they are a terrible host and you're getting ratelimited

#

interactions have different ratelimits than gateway

green kernel
#

Is there no way to edit an ephemeral message?

little cobalt
#

you can edit a ephermeral message

green kernel
#

Something like

await interaction.message.edit(view=self.view)

throws a 404 not found error when used in an ephemeral context

#

can edit_original_message or edit_original_response work instead? πŸ€”

#

Figured it out. Have to defer the response before editing.

fleet cedar
green kernel
#

Ooh, good to know

green kernel
#

Can @commands.Cog.listener(...) be used to make custom events? πŸ€”

#

If so, how? Bot.dispatch() seems like it can't be awaited so I'm not sure if that's how I'd do it

shell radish
#

create your own event loop

green kernel
fleet cedar
#

It's pretty much
bot.dispatch('my_event', ...) and
@Cog.listener('my_event')

#

Case sensitive btw iirc

green kernel
#

but yeah I've decided to just roll my own little event thing

lapis condor
#

Anyone having issues sending embeds using await message.channel.send(embed = embed) and getting this error discord.errors.HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message
if i use await ctx.response(embed = embed) it will send embeds however.

daring valve
lapis condor
# daring valve Use ctx.respond instead of response And I think your embed is none or embed is e...

This is the code for reference, it is supposed to detect "bad words" sends the embed and deletes the message.

async def on_message(ctx):
    print(banned_word)

    if any(x in ctx.content for x in banned_word):

        bad_word_embed = discord.Embed(colour=discord.Color.blurple(), title="Auto mod", description=f"Their was a bad word detected and this message has been deleted.\n\nRepeated offenses may lead to a ban.")
        await ctx.channel.send(embed = bad_word_embed)
        await ctx.delete()
        return```
hazy turret
#

Does anyone have any idea how to recognize secondary accounts?
Because the member object only has the 'create_at' which you could check but with that you can't really tell if it's a secondary account or not.

hazy turret
little cobalt
#

Why should that be possible?

#

You would have to check for something like an ip

hazy turret
heavy sky
#

So, if one account gets banned from a server, all accounts in that ip will automatically be banned

ancient cosmos
#

Would it be appropriate to bump or link to a help thread I posted about a week ago that didn't get any responses? I'm not sure if the information I gave was unclear or whether the issue was just difficult to pin down, so I'm open to trying to rework/improve the question, too.

lofty parcel
#

Just bump.your thread

ancient cosmos
#

No worries, just wanted to make sure that was okay

strange hamlet
#
from discord.ext import commands

intents = discord.Intents.all()
intents.messages = True

client = commands.Bot(command_prefix='!', intents=intents)

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

@client.command()
async def buttonFunction(ctx):
    button = discord.ui.Button(label="Click This To Open A Ticket.", custom_id="button_click")
    view = discord.ui.View()
    view.add_button(button)
    await ctx.send("Click The Button Below To Open A Ticket")

client.run('TOKEN')

The code is returning an error saying that "discord" has no attribute name ui. What am I missung?

strange hamlet
#

sure

#
------------------ --------
aiohttp            3.8.5
aiosignal          1.3.1
async-timeout      4.0.3
attrs              23.1.0
beautifulsoup4     4.12.2
blinker            1.6.2
bs4                0.0.1
charset-normalizer 3.2.0
click              8.1.7
colorama           0.4.6
ffmpeg-python      0.2.0
Flask              2.3.3
frozenlist         1.4.0
future             0.18.3
idna               3.4
imageio-ffmpeg     0.4.8
importlib-metadata 6.8.0
itsdangerous       2.1.2
Jinja2             3.1.2
MarkupSafe         2.1.3
multidict          6.0.4
numpy              1.24.4
package-name       0.1
pandas             2.0.3
pip                23.2.1
py-cord-dev        2.5.0rc5
pycord             0.1.1
python-dateutil    2.8.2
pytz               2023.3
setuptools         68.1.2
six                1.16.0
soupsieve          2.4.1
typing_extensions  4.7.1
tzdata             2023.3
Werkzeug           2.3.7
wheel              0.41.2
yarl               1.9.2
zipp               3.16.2```
lofty parcel
#

Try reinstalling py-cord ig

strange hamlet
#

py-cord dev?

lofty parcel
#

Yes

strange hamlet
#
Traceback (most recent call last):
  File "C:\Users\itama\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:/Users/itama/Desktop/Pycord/main.py", line 15, in buttonFunction
    button = discord.ui.Button(label="Click This To Open A Ticket.", custom_id="button_click")
AttributeError: module 'discord' has no attribute 'ui'

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

Traceback (most recent call last):
  File "C:\Users\itama\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\itama\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\itama\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module 'discord' has no attribute 'ui'```
#

that's the error I got again

little cobalt
strange hamlet
#

oops

#

yeah, uneccesarry

lofty parcel
#

No idea then lol

#

That's weird

cursive leaf
#

what could be causing my tasks.loop function to just stop executing

errant trout
cursive leaf
#

kk

ancient cosmos
#

If I decorate a callback function with @commands.slash_command and do not provide an argument for the decorator's options parameter, at what point in the execution flow does SlashCommand._validate_parameters get called to populate the command's options (via SlashCommand._parse_options)?

The only place I can see _validate_parameters get called is during SlashCommand.cog's setter, and I can't find anywhere in discord.commands.core.py where self.cog = [something] on a SlashCommand object. (There's cases like line 608 here, but that's a SlashCommandGroup, not a SlashCommand.)

sour musk
#

Heya, i decided to make a color customization by using the discord form and got stuck on the output of the variable to insert into the embed
discord.Color

sour musk
#

I'm confused

#

It's one thing when, when creating a group of commands, you do not give a single command in this group, another thing is when you catch a kernel error from the library

ancient cosmos
#

Don't worry about it; I found a different way to accomplish what I was trying to do, and that made the research I was doing in the source not necessary anymore

sour musk
#

OkayrooAww

#

I have not yet reached the level of psychosis and creating my own palette with a handful of everything, I need help, because I really forgot everything blobpain

red mist
sour musk
#

here it will rather sound more correct using the standard disk code to translate the string into color without using a long filter
red = 0xff000
Green ...
And ect

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

        self.add_item(discord.ui.InputText(label="Topic"))
        self.add_item(discord.ui.InputText(label="Text (only 2000)", style=discord.InputTextStyle.long))
        self.add_item(discord.ui.InputText(label="Image link", required=False))
        self.add_item(discord.ui.InputText(label="Color(red/green/blue)", required=False))
        self.add_item(discord.ui.InputText(label="Footer", required=False))
    async def callback(self, interaction: discord.Interaction):
        colors = self.children[3].value
        
        embed = discord.Embed(title=self.children[0].value, description=self.children[1].value, color = discord.Color.#here idk)
        embed.set_image(url=self.children[2].value)
        embed.set_footer(text = self.children[4].value)
#

@red mist upvote

red mist
#

color should be = to the hex code you put in as a variable, discord.Colot is only used to use the default colors included, do pretty much you can just make your variable red = hex color code with ofc the 0x Infront and then just use color = red

#

@sour musk

sour musk
#

as far as i know that discord.Color can use format discord.Color.red() but for Color any external variable will throw an error

#

but at least one of the arguments either does not exist or is missing

red mist
#

the hold on.

sour musk
#

can try variable in state .join(f"{colors}")

red mist
#

If I were to set color = em_green

#

Then my green would be

#

em_green = 0x2ecc71

#

not a string

#

Just that.

#

not a string

sour musk
#

okie, i rebuld code for format hex

red mist
#

you can use hex for custom colors

#

But ultimately you can also use color = discord.Color.red() yk

#

For default built in colors

sour musk
#

I planned to replace the last of the usual colors with custom names

red mist
#

I think you could also use RGB but I'm not sure wether or not you still have to convert that to Hex first

errant trout
red mist
#

Wait that's a thing?

errant trout
#

you can try it yourself

red mist
#

holy shit I didn't know that LOL

errant trout
#

as long as you don't include the leading #

red mist
#

Ye ye ofc but

#

lmfao

sour musk
errant trout
#

i mean

#

yeah i guess, but what can you do GuraShrug either deal with potentially bad user input to allow freedom, or restrict their choices to set colors

#

ultimately up to you

sour musk
#

indianred = 0xcdscsc
lightcoral = 0xf08080
salamon = 0xfa8072
darksalamon = 0xe9967a
lightsalamon = 0xffa87a
crimson = 0xdc143x
red = 0xff0000
finebrick = 0x822222
darkred = 0x8B0000

pink = 0xffc6cb
lightpink = 0xffb6cf
hotpink = 0xff69b4
deeppink = 0xff1493
mediumvioletred = 0xc71585
palevioletred = 0xdb7093

I have small list but if it is displayed in a single change and a simple filter without db ...
If colors = x
color = 0xff
elif ...blobpain

#

and output as second file

errant trout
#

im sorry but this looks miserable

#

just look for a hex code regex and tell the user to re-enter their colour if they did something wrong

sour musk
#

Ohh my bot's handwriting is off the charts doggokek
Thank you, I will try to implement> write your own 0x...

round heart
#

Sanity check: Are Option(choices=) fully set on command initialization, or can it be evaluated when the command is invoked?

ancient cosmos
#

Fully set as far as I've been able to tell

errant trout
#

you have to use autocomplete otherwise

ancient cosmos
#

If you need a workaround you need to use autocompletes or a View (which you could pass state into)

sour musk
#

and so I think to try to create a database of colors, it will be torture but shortens the code
it remains to remember how to write in jsonkek

round heart
#

Trying to avoid a view for just a single input. autocomplete is fine, but a little superfluous for the value. Really just need to evaluate it when the command is about to be invoked.

#

Anyway, thanks to all πŸ™‚

sour musk
#

Ummm i think i can use itblobpain @errant trout

devout mirage
#

tf does this mean```py
File "/home/container/cogs/fun.py", line 440, in setrole
data[f"{ctx.guild_id}"].update({"role", role.id})
ValueError: dictionary update sequence element #0 has length 4; 2 is required

fickle salmon
cloud bloom
#

What's the diff between discord.User and discord.Member?

#

Are they the same?

shell radish
cloud bloom
shell radish
cloud bloom
#

ok thx