#Basic Pycord Help
1 messages Β· Page 7 of 1
yeah
ill try it
π
Hi om
Mood
show pip list
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
ive just uninstalled discord and discord.py
intents = discord.Intents.default()
AttributeError: module 'discord' has no attribute 'Intents'
Try to re-install py-cord
Nice
Uninstall discord and discord.py
that will cause lots of troubles down the road
And then reinstall py-cord
is there any trick for using autocompletions for Optional arguments?
can i have a tasks.loop within a button class?
Why? I'm really curious
You could start a task within the button class. I don't know why it would need to be within the button class.
You would have to explain more. Is something not working right?
Autocompletions are for required arguments right? I want to use them for an optional argument for a slash command.
async def get_command():
pass
@slash_command()
@option("lol" autocompletion=get_command)
async def ping(ctx, lol:Optional[str]="lol"):
pass
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
Alr
Hello, is it possible to retrive label and value from selected option in select_callback?
Here's the dropdown example.
@red pagoda
Isnt this one only retrieving value?
Autocomplete works fine with optional arguments.
Just fyi its autocomplete not autocompletion
alr
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)
Guild.get_member Remember that you may also need to try fetch_member too. With the member object you should be able to get roles
so would it be guild.get_member.roles
?
yeah, except you would need to actually pass a user id
thanks π
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]
"NoneType"
?
how is bot defined?
Hi there!
Does anyone have an idea how to delete this message automatically?
bot = discord.Bot()
if thats what you mea
how do i fix that?
discordid is not None correct?
Somehow your bot is None
my whole code is here #1144683670066704505
is there a way to fetch the emblem of a role in pycord?
π
okay great, tyvm
also what is the icon stored as
Not sure. You will have to try it out
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?
I have not got any reports of bugs in the master branch that are not also in the latest stable release. I would disable any sort of auto update so if a new bug does arise you will not pull it from the latest commit.
thanks
get_user is not an async function
But user.send is. Await that
okk
[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]```
Hmm how are you running the bot?
what
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
Show your pip list
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```
actually
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'```
Show your code
The user is None
If you used get_user then it not in the cache
And you have to fetch the user
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```
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]```
How do you run the webserver and the bot?
You're doing commands.command and I think it's trying to add it. But it's a Discord.Bot instance, it only handles slash commands
You run the bot right? π
There should be 1 of bot.run(...) or await bot.start(...) somewhere in your code. Where is that?
bot.run(os.getenv('TOKEN'))
I can already only tell by your code that you use Replit
thanks 
And the webserver?
i updated @commands.commands to @dicsord.bot
discord.errors.ExtensionFailed: Extension 'cogs.greetings' raised an error: TypeError: 'module' object is not callable```
What
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'))```
Havent Jack already open a thread?
Yes
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
Besides the fact I didn't ask you to replace it.
Do you understand what each thing is?
discord.Bot is the bot instance
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
commands.command doesn't work for discord.Bot because it doesn't handle prefixed commands. And that's why it might be erroring
There is a async one for Flask
right, so the documentation is wrong? o7
Quart is just async flask 
No?
The bot instance you're using doesn't support prefixed commands.
this one?
?tag clients
No tag clients found.
followed this: https://guide.pycord.dev/popular-topics/cogs
Cogs, often known as modules or extensions, are used to organize commands into groups. This is useful
?tag client
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)
yea ok x3
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
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?
Whatever they select is just for them
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:
to add args to the slash command do I just need to add extra args to the function or is it something else
Yes
Thanks
any ideas why?
Try adding print(error, error.original, type(error)) at the start of the function
Iirc, Application command errors get wrapped inside a different error or some weird stuff like that
.rtfm on_application_command_error
discord.on_application_command_error
discord.ext.commands.Bot.on_application_command_error
discord.ext.commands.AutoShardedBot.on_application_command_error
discord.AutoShardedBot.on_application_command_error
discord.ext.bridge.Bot.on_application_command_error
discord.Bot.on_application_command_error
discord.ext.bridge.AutoShardedBot.on_application_command_error
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?
Is voice.pause an async function?
.rtfm VoiceClient.pause
i didnt try to fix that because it says NoneType so its not something that i can interact with, i think
oh my god.
it was just not using async
im dumb
thanks for the help
Np
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 
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)
.viewwait
# 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)
Just what you need from what I understand
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)
Looks fine for me
Will check thx
Should I serialize discord Messages and Channels using repr() or using their IDs?
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 ?
Temporarily or you never want any prefix commands?
I never want to use a prefix command
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?
yes
yea
Will will also likely have to switch command decorators to
@discord.slash_command
Okay everything works thanks! π
@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?
you need to use ctx.respond for slash commands. instead of msg = await channel.send(embed=embed), do py await ctx.respond(embed=embed) msg = await ctx.original_response() await msg.add_reaction("π")
breaks, doesnt send it in the intended channel
ah, right, I missed that you wanted to send it to a certain channel. You'll have to send the message to the intented channel + respond to the interaction for it to not throw an error
Some thing like
await ctx.respond(content="Your Suggestion Was Posted") could work
yeah i did that, sends but message above it still errors
one sec
can you send your code
@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("π")
You have to use ctx.respond not ctx.send to respond to a slash command
alr works now, thanks
π
another suggestion is to add ephemeral=True to the respond. This will hide it from other people so it does not create spam in that channel
alr
doesnt seem to work
@bot.slash_command(description='suggest ton features!', ephemeral=True, guild_ids=['1144777754894676081'])
You need to pass it to ctx.respond
oh alr
Add it to the respond
await ctx.respond("Suggestion sent!", ephemeral=True)
Follow up question, how do I delete that select option and replace it with embed and still keep input so I dont get "Couldnt load message"
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] ?
yes
Do attachments within slash commands have a size limit. If so, do you know what it is?
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.
How do I do it?
it might be the same limit as a normal attachment for the user
you could try it and see
Just try and except. I think if the user clears the message you no longer can modify it. Also if you timeout is 15 minutes (900 seconds) or above I would lower it to at least 890 to give some time for latency when the interaction token expires
How would I make my bot fetch a list of all roles which have an emblem
Some classes are just there to be data containers, this lists them. Unlike models you are allowed to create most of these yourself, even if they can also be used to hold attributes. Nearly all clas...
I had it set for 600. But I thought the View model would take care of the try/except? I don't have any user code for this, just passing timeout=600 into super().__init__() of my View
If this is possible
Just loop through https://docs.pycord.dev/en/stable/api/models.html#discord.Guild.fetch_roles or roles and check for the role icon
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
I don't think the base View does this
I know the loopy thingy how would I check for the role icon
for role in roles:
if role.emblem:
like that?
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - Pycord-Development/pycord
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
...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
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.
Can I also specify a list there or just a single option?
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
how do i make a task loop at utc 0 every day
ext.tasks.loop has a time kwarg.
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
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)
keep fucking up the time kwarg
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
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)
Did you also add the intents to your bot?
yup
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?
intents = discord.Intents()
intents.members = True
intents.presences = True
intents.message_content = True
bot = discord.Bot(intents=intents)
no intent errors
And also at the Website?
just the send with my embed
You use get_channel
?Tag get_x
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.
ah
@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
leave out hours=24 it will run at that time every time that time occurs. (IE every day)
if bot.get_channel(1145759009127805039) == None:
channel = bot.fetch_channel(1145759009127805039)
``` @lapis dock ?
You can, for each of the options in the select that should be selected you need to set default=True
YEs except you would need to save the get_channel to a varible too
Is the whole thing then also visually displayed ?
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
my_options = [SelectOption("Red"), SelectOption("Green", default=True), SelectOption("Blue", default=True)]
discord.ui.Select(options=my_options)
Do you have something like this? Im not exactly sure what you mean
what error does it give if you await it?
Expression cannot be assignment target
@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 '='?
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
yeah sorry, got it working now
any way to tell chronological order of reacters based on reaction.users() method?
like is the .users() method return reacters sorted someway?
How do i add a repeating thing which pulls all the roles from a server every 5 minutes or so
Tasks
Here's the background task example.
No
reaction.users returns a Member or User object
A list of members right? Wanted to see if the members r sorted by time, but it seems theyr sorted by member id
its probably how it gets stored by discord
Hey, where can I find any info about an output like this <function Client.fetch_user at 0x7fc2626c6820>?
I'm not sure what you mean. Something like that is what's printed out when you try to print a function
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
so i need to look under Client.featch_user, in the docs
yeah, that function is located at discord.Client.fetch_user
can i ask what you're doing with that output, though?
I want to remove a role from a user, but I only have the id from my db
Can you show us your code, or would you prefer to figure it out on your own?
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
That's fine. Do you mind editing it to be in a code block?
?tag codeblock
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.")
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
How are you getting the output you showed us earlier?
print(guild)```
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?
this is the code that's running, I can only send the whole file with the setup of the cog
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.
Can you show us some of the code you're using?
And what exactly do you mean by beatboxing?
@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?
No. You would almost definitely get ratelimited.
even if i set it to 10 seconds nothing happens
that doesnt look like python
at the end is where the magic happens
That's Lua. I think you may be in the wrong server.
yeah like i said in another language
yea well our discord client doesnt support voice receiving yet which im trying to change
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?
it uhm kinda has nothing to do with pycord other than pycord has support for voice receiving
ok, got it! Thanks^^
In that case there's not much we can do. This is a Pycord support server. We can't support you if you aren't using Pycord.
okay ill see
you can always check the source code tbh
thats what im trying to decipher right now
Make sure you're starting the task somewhere. I forget exactly what that line is to do that though, one moment
It's simply
your_function.start()
and this should be at the end right?
Do that once your bot is already running, though. Preferably in an on_ready or similar function
okay sure
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")```
you might need to clarify, Iβve seen people copy and paste it and say it doesnβt work
I provided a link to the guide, as well as an example from the guide
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
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
I just have, bot = discord.Bot()
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
how would I do self.get_channel?
You wouldn't. You'd use your bot object. bot.get_channel
no, you'd still need to do channel.send because you are calling the send method of channel
in my case, how would i fetch all of the roles of a server?
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
It's recommended to use get_guild though
how do you make a dedicated error handler for a single command?
like is there a decorator for it?
if your command name is stupid, then use @stupid.error
tysm
it was annoying me cuz I was getting errors from that
but i forgor to place
the error parameter
"@stupid.error" definitely decorates all my mistakes
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
Is there a good way to get sort of a 'main' colour of someone's pfp and set it to be the embed colour
You'd need some image library
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
Is this the simplest way?
or
I think this is the simplest way lol
Just pass the link and it will give you embed color
Embed(colour=await dominant_color(user.display_avatar.url))
It is discord background color iirc
Oh wait, no
You can use Color.embed_background()
Tbh I forgot why I use exactly this color
Β―_(γ)_/Β―
Funny number I guess
also, could you show your imports here?
import aiohttp
import colorthief
from asyncache import cached
from cachetools import LRUCache
from io import BytesIO
thanks
Constructor parameter should be str
do you know what this means?
full traceback please
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))
shouldnt it be display_avatar.url
I was sort of thinking that because I used that earlier
Here he said pass a link
Ah
Sorry, I used my internal user class π
@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
for role in server.roles:
AttributeError: 'coroutine' object has no attribute 'roles'
hm
I tried switching it to fetch_guild
await fetch bruh
.
wait, you clear the list every iteration π
- I think you can just
serverroles = server.roles
is server.roles already a list?
yes lol
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
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?
Do I need any more permissions to add a role?
The bots role is above the role I want to add
And what are the bot permissions?
Hm?
At the Server
I havent declared them anywhere yet
do I need to?
Do you try it with an interaction or where do you do it?
In a command
just a slash command
do you do it with ctx.author.add_roles? or how
for a slash command you dont need intents
guild.members is returning a list of members right?
hover with your mouse over the members
I'm currently not at my PC so I can't
Yes it does
I don't even have a Mouse on my phone
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

uhm, what?
I'm not sure, but making embed generator with slash commands is not the best idea imo
What?
Because slash commands has options limit of 25
Same for embed fields
Yeah, but embeds has name, text and inline
Yea
- author, title, description, footer and so on
simple no more than two fields in command
my example already has the maximum that the bot and hosting will digest without an explosion
What do you think about interaction modals?
Maybe ui components
Use discord forms
Really odd lol
I did not go deep into this thing and in my opinion it has problems with forwarding
wdym forwarding?
Do you use a translator?
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
Voice translation 
I tried to do it in English for input, but it turns out 4 times worse
I can speak with you in russian only in dms because lala banned Cyrillic for some reason 
L
@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
highly likely an api ratelimit.
add/remove roles accepts multiple roles in a single api call. refactor your code logic to just usee 1 add api call and 1 remove api call
you are currently doing it inside the for loop
I tried earlier appending the roles with emblems to a list but at the same point of failure it didnt seem to work
The list was empty
how were you doing it?
oh wait. you break the for loop
then ratelimit shouldnt be an issue imo
sorry
It was like
author_roles_emblems = [role1 for role1 in ctx.author.roles if role1.icon]
hmm
well my issue was
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
you thought of anything?
im clueless to be honest...
nothing obvious ngl
you could enable logging and see if it is actually a ratelimit issue
.logging
Pycord logs errors and debug information via the logging python module. It is strongly recommended that the logging module is configured, as no errors or warnings will be output if it is not set up...
I think it is
Im not sure how to tell 100% if it is
But i feel like it is
How would I fix this?
if you enabled logging then you will see a message in logs that endpoint xyz is ratelimited, trying again in some seconds
The logs are full of a lot of hard to read text, is there any way to simplify it?
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?
also if it is ratelimit - how would i fix it?
it's not a ratelimit
The library handles ratelimits by itself
So what is the issue in my code?
Ive been spending so long I can't see anything that it may be
Dunno, didn't read your issue
Essentially in short
my command checks if the user has a role with an emblem and if they do it removes it and adds a role specified by the user
Thought when the command is ran the 3rd time it doesn't remove the role with the emblem it just adds the specified one
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?
__init__
fair enough ty
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
what does server.roles return? an empty array?
server.roles or server_roles
what I said
it returns all of the roles in the server including supporter
however i want only the roles with icons
try using bot.get_guild
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
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
server_role not server_roles
oh oops
Steam Verified
Artist
EUSL Veteran
S8 Challenger Winner
S8 Bronze
S8 Silver
S8 Gold
each iteration
so the role isn't even there
you got any idea why it may not exist? π
Β―_(γ)_/Β―
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?
not really. Just count it yourself
Well I don't even know what the sent structure is, so I can't count.
the 1 means row 1
the 0 means item 0
the option means option 0
value means value
Turns out I'm dumb.
I do wish it was easier to see raw payloads to Discord, though.
Hello! How can I replace the help command with my own?
bot = Bot(help_command=None)
getting a no module named discord error
Did you install the library? 
Thank you
well yh
Show your pip list
pycord and python-dotenv
I want an actual screenshot
thats literally all i've installed
its on a server
is the pycord library on replit
what. If you're wondering if you can install it on replit, then yes. You can access all pypi libraries on replit
Is there a way to limit this list of roles to only certain ones i want to show?
Not atm
youd need to use an autocomplete and parse it by yourself
damn
which one is for slash commands buttons etc
the library is called py-cord
?tag replit
Installing Pycord with Replit (only use replit as a last resort) - pycord-replit-install.md
@atomic mortar ^
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.
it didn't go anywhere...
.rtfm discord.Bot.slash_command
so my autocompletion is
lying
thats possible
it is just this
oh had discord.py on my pc
No its not!!
Is there any other way to detect if the bot is mentioned in a text message other than checking every new message for mentions?
you can poll the channel history, but that's basically the same thing
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?
I thought that discord added an alternative when they tried to remove the message content intent
nope
you just check it in on_message
Alright thanks
Does anyone know a solution?
π§
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...?
Docs are good if you have a basic understanding of how to use a package/library
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!
chill voxy
Im sorry but wtfff
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
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
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?
Maybe youre making a lot of API calls which causes the discord API to give your bot a timeout
Actually I should not get into any rate limit
What does the task even do?
Also
You can use the logging package from python to check what your bot is doing
The task only edits one embed:
await message.edit(embed=embed)
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')
Maybe your bot is doing something else .-.
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
Does discord have a special error for the timeout or rate limit that can be caught ?
Idk I genuinely dont know, which is why I used to do this log file thingy. Worked great for me
actually I forgot to mention, it makes 2 files because I had 2 log files being made lol
youll see when you understand the code xd
I have implemented a logger. Will run the bot again and see what comes around Thanks! π
Nice :)
This, I am not going to send a link to the server here.
So....
I cannot see any of my slash commands anymore
with my main account I can see them but not with my alt
guild slash command permissions?
could be admin commands or dev commands won't be shown
Dunno
no
0 permissions
basic slash commands
uhm the what, either your main is blacklisted, or your alt is whitelisted by your bot dunno
Restart/update your clients
is there a documentation with all the features of pycord listed? if so where can i find it?
mhm
Its working at the test server
so weird
Synched only to a guild?
no they are global
the fk
yea...
yea
What
Pycord is a modern, easy to use, feature-rich, and async ready API wrapper for Discord. Features: Modern Pythonic API using async/ await syntax, Sane rate limit handling that prevents 429s, Command...
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
Was gonna remind you of the DCV I made
I had such a hard time making the dark and light theme work LOL
Made it and never used it :') well ok I did use it but yk
only for that one scenaria
I still want to create something for the OpenDTU project
bot does not want to connect (will upload image)
need help to correct this error
read the error
im dumb
i dont understand the error
python syntax errors are a pain to understand
im not at that level yet
fixed it
you should add a short video to the readme
is there a limit, how many embeds can be given to paginator at once?
each message can only have 25 embeds iirc
could it cause an index error, if it gets more?
just the amount of memory you have
Your message will not send if each page has more than 25 embeds iirc
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)
you can have as many pages as you want
the only limit is your system's memory
damn. then my error must be somewhere else. Thanks!
you should probably just send the error
I will, next time it shows up.
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".
do you use a prefix command?
No, this is a role command, when someone clicks on a reaction they get a role and this embed should be send to them.
Is there a max number of options a slash command can have?
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.
anyone know how to bypass discord.errors.HTTPException: 413 Payload Too Large (error code: 40005): Request entity too large
sounds like more like your code has issues than anything else
Truncate the message before sending it
what mean
it means make the message shorter
its a file tho
then your file is too large
the size limit is supposedly 25 MiB for the entire request
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?
is @fleet cedar 's pull request for the paginator still open? bec. I can't find the PR
You're already in a thread
Stop crossposting
It's just annoying
Which one?
What was the topic?
I have made multiple prs for paginator lul
that you have more options to edit it
Ah
It's there on the dev release
See #library-updates
Ok thanks
Intents
And you just leaked your token
Congrats
?tag intents
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)
It is intents.messages
I don't know what you're doing without seeing code
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?
Whats your pycord version
1.7.3
That's pycord
I used to develop bots in 2021, I forgot most of it and now I want to start again
oops - I installed something called pycord
You're probably using dpy or something
Did you uninstall other discord libraries
done
And re install py-cord-dev
You should be good to go
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('/')
what's the error?
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
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."
That's not what the error asks for. You need to go to the developer portal and enable privileged intents
it works now?
and change your token again
already did
how can I change the nickname of a member?
I can't seem to find it...
oh got it xD
member.edit
yep lol
How do you supply an announcement channel as the type for the @option decorator?
@option("channel", TextChannel | Thread, description="...")
You can use this I guess, with discord.ChannelType.news
Command Permission Decorators: Commands: Shortcut Decorators: Objects: Attributes full_parent_name, qualified_id, qualified_name. Methods@ after_invoke,@ before_invoke,@ error, def get_cooldown_ret...
It doesn't work though:
@option("channel", ChannelType.news | TextChannel | Thread, description="...")
It should work if you do something similar to this:
@bot.command()
@option("channel", channel_types=[discord.ChannelType.news], description="...")
async def command(ctx, channel:discord.TextChannel):
await ctx.respond(channel)```
Using channel_types doesn't work either
It doesn't seem to have any effect
can you show your code?
@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
And you want channel to take an announcement channel?
So I've tried adding ChannelType.news to TextChannel | Thread and also tried adding it into the list for the channel_types kwarg
Yes
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
It still doesn't work
The news channel doesn't show up in Discord as an option for the param
hmm, weird, that worked for me
Could you pls send ur code
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
Strange, it shows all channels for me when I do it
What version of Pycord are you on?
Alright, lemme try updating and see if that fixes it
That sorta fixed it
It works outside of cogs, but not inside
oh, nice
Thanks for your help
No problem π
I was already close to mention that version to test it
Seems to be working fine in cogs on 2.4.1 for me though...
Anyone got any ideas on this?
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?
What you're looking for is called ephemeral I believe
I think the reply example displays an ephemeral reply iirc
Here's the reply example.
Oh, not that one
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?
you're not sending anything?
i think the default might be MISSING
Sorry, misleading - there is a response, just that view is specifically None
discord.interactions.send_message() has view as a default of None. But I suppose it's possible it's not using that method
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
there's probably a good reason for it
other than send and edit using the same handle_params function
which we can probably fix in 3 minutes
Why do my prefix commands suddenly stop working?
Is there a general bug with Discord at the moment?
why did you also add content=?
?
for text but not an embed
Does anyone have any idea why all of my bots suddenly stopped working without me changing anything?
Slashcommands still work without problems
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,
)```
messages β message_content
Oh damn thanks!
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.")
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
Is there no way to edit an ephemeral message?
you can edit a ephermeral message
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.
You can use interaction.response.edit_message
No need to defer for using that
Ooh, good to know
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
create your own event loop
Why? :(
Yes
Dispatching will schedule the event handlers in the event loop
It's pretty much
bot.dispatch('my_event', ...) and
@Cog.listener('my_event')
Case sensitive btw iirc
apparently i have to prefix the event name with on_ otherwise it complains
but yeah I've decided to just roll my own little event thing
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.
Use ctx.respond instead of response
And I think your embed is none or embed is empty and that's why you get this error
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```
Ah yes
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.
You mean for alt accounts?
I want to check that if someone is banned from the server and then creates a second account that he can not do nonsense with it then again on the server.
I can't get to it via the Discord account without further ado.
All server bans are based on IP, not per account
So, if one account gets banned from a server, all accounts in that ip will automatically be banned
Okay
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.
Just bump.your thread
No worries, just wanted to make sure that was okay
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?
Pip list?
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```
Try reinstalling py-cord ig
py-cord dev?
Yes
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
Why did you add message intents to all intents?
Uh
No idea then lol
That's weird
what could be causing my tasks.loop function to just stop executing
Any unhandled exception
kk
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.)
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
Can be more human language and more briefly 
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
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
Okay
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 
So... You pretty much want to know how to set custom colors?
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 
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
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
the hold on.
can try variable in state .join(f"{colors}")
If I were to set color = em_green
Then my green would be
em_green = 0x2ecc71
not a string
Just that.
not a string
okie, i rebuld code for format hex
you can use hex for custom colors
But ultimately you can also use color = discord.Color.red() yk
For default built in colors
I planned to replace the last of the usual colors with custom names
I think you could also use RGB but I'm not sure wether or not you still have to convert that to Hex first
if you need to convert a HEX string to a compatible colour, use int to convert to base 16py white = "FFFFFF" embed = discord.Embed(color = int(white, 16))alternatively as described above you can do 0xFFFFFF for example instead, but that only works for hardcoded values
Wait that's a thing?
you can try it yourself
holy shit I didn't know that LOL
as long as you don't include the leading #
but for this you will need to create a rather bold input filter since the person in the form will write by hand
i mean
yeah i guess, but what can you do
either deal with potentially bad user input to allow freedom, or restrict their choices to set colors
ultimately up to you
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 ...
and output as second file
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
Ohh my bot's handwriting is off the charts 
Thank you, I will try to implement> write your own 0x...
Sanity check: Are Option(choices=) fully set on command initialization, or can it be evaluated when the command is invoked?
Fully set as far as I've been able to tell
set on initialization
you have to use autocomplete otherwise
If you need a workaround you need to use autocompletes or a View (which you could pass state into)
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 json
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 π
Ummm i think i can use it
@errant trout
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
so that can just be data[ctx.guild_id], but can you show me what's in data?
What's the diff between discord.User and discord.Member?
https://docs.pycord.dev/en/stable/api/models.html#discord.User and https://docs.pycord.dev/en/stable/api/models.html#discord.Member
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
Are they the same?
one is guild specific, one is global
Which is which
member is guild
ok thx
