#Basic Pycord Help (Quick Questions Only)
1 messages · Page 12 of 1
my client doesnt want to
(client as in a literal person)
ye
you could just regenerate the view and edit over the original one
please don't
well i already said
just generate a new instance of the view and edit over the first message
generate new instance means the attributes reset right?
yeah
you could just add more checks to the callbacks
or add new arguments to the init to preload attributes
like py class V1(View): def __init__(self, test1=None, test2=None): super().__init__() self.test1 = test1 self.test2 = test2 so now you can optionally pass in the initial value for test1 and test2; if you don't, then they'll be None like before
it's not a coro
It’s just self.stop()
A coro is awaiting and calling a function
all good
how do i make view.wait() persistent?
How do i add a role?
create a role?
or give role to user?
Give
user.add_roles(role)
AttributeError: 'User' object has no attribute 'add_roles'
show me the code
where should we define the SlashCommandGroup class in cogs?
AttributeError: Option does not take min_value or max_value if not of type SlashCommandOptionType.integer or SlashCommandOptionType.number
async def lock_time(self, ctx, time: Option(int, 'Enter a time in Seconds', min_value=3, max_value=20, required=True)):```
why is it giving me error?
it worked fine when store was set to true while loading cogs
when i change to false, this error comes
can someone tell me what are these sort of slash command options called so i can utilise it i nmy own code?
^^
yea got it
How do we make these commands?
User and message context commands
#I tried using this
@bot.user_command(guild_ids = [id], name = hello)
async def hello(ctx, message : discord.Message):
await ctx.add_reaction("👋")
But it didn't work
I wanna know why does this error show up whenever I run my bot
What is this error
i have a line of code
super().__init__(150, 5, 5, 3, 'Dark', 'Light', 'Tank')
which returns an error
raise TypeError(f"expected Item not {item.__class__!r}")
TypeError: expected Item not <class 'int'>
in my command but when i try it outside of my classes it works fine? my command is for a combat menu with buttons and i have my combat stats (hp, atk, etc) in a Combat view and my view in CombatView(discord.ui.View, Combat)
Okay so i think about it, it will probably work for me but what about my host ? I can't change the core file of my host :/
If I delete the message with delete_original_message after a few minutes I am fine. But if I delete it after a few hours it doesn't work, could it be because it is no longer cached or something? I get the following error:
2022-08-19T07:24:21.910953+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/site-packages/discord/interactions.py", line 441, in delete_original_message
2022-08-19T07:24:21.910953+00:00 app[worker.1]: await func
2022-08-19T07:24:21.910954+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/site-packages/discord/webhook/async_.py", line 213, in request
2022-08-19T07:24:21.910954+00:00 app[worker.1]: raise HTTPException(response, data)
2022-08-19T07:24:21.910955+00:00 app[worker.1]: discord.errors.HTTPException: 401 Unauthorized (error code: 50027): Invalid Webhook Token
you should be able to
Nah my host Say that i can't :')
import discord
class Test(discord.ui.Button):
def __init__(self, custom_id):
super().__init__(label ="Test", custom_id=custom_id)
async def callback(self, interaction: discord.Interaction):
await interaction.response.send_message(interaction.custom_id)
How can I use such a button after restarting the bot?
Here's the persistent example.
poll = discord.Embed(title=title,description=f':thumbsup: {option1} \n\n:thumbsdown: {option2} ' , color=0x20B5E1)
poll.timestamp = datetime.datetime.now()
await ctx.respond(embed=poll)
await poll.add_reaction('👍')
await poll.add_reaction('👎')``` Why arent the reactions being added?
Error?
you are trying to add reactions to... embed object?
you should add them to message
What would i replace poll with?
msg?
alr
poll = discord.Embed(title=title,description=f':thumbsup: {option1} \n\n:thumbsdown: {option2} ' , color=0x20B5E1)
poll.timestamp = datetime.datetime.now()
msg = await ctx.respond(embed=poll)
await msg.add_reaction('👍')
await msg.add_reaction('👎')``` No error? No reactions?
second
you need the original_message()
Still confused sorry, Where would i put this/What can i do with it?
you basically need to use msg.message, ctx.respond returns Interaction, not discord.Message
Ah alright
how do i reply to a button press so only the person who clicked it can see it
await msg.message.add_reaction('👍')
await msg.message.add_reaction('👎')``` what did i do wrong here?
🤔
nothing, i suppose
may be im wrong, second
well, just msg.add_reaction should work
its kinda strange, but, well. It worked for me
🥴
it won't for the first response because, as you said, that returns an interaction
did you defer?
yes, i think that's the reason
well it has to be that way 
in early betas you couldn't even use respond twice like that
standing here i realize?
anyway if it's first response, you need to do await msg.original_message() to get the original message
dude was right tho, im stupid
Sorry, Where would i put this?
^^
How can I make a permissions error handler
elaborate
go on
on_member_remove this will be called when a member gets banned / kicked
well
right?
whenever a member is removed from the guild
yeh so it could be by ban / kick
they can also leave themself
syncing with the audit log u can tell that
yes but using audit logs u can tell that
for example
i'm not sure if ban fires it because there's the separate on_member_ban event
async for i in member.guild.audit_logs(
limit=1,
after=datetime.datetime.now() - datetime.timedelta(minutes=1),
action=discord.AuditLogAction.kick
):
this will tell if a user gets kicked
YES that's why i was going to ask u why there's a on_member_ban
yeah, but you should sleep first
wym sleep
sleep what?
so you might miss the log entry
I been always using this and it always worked 🤔
it might but there's a chance it'll miss it eventually
how long should i sleep it for?
Yes. it's about antinuke so speed is surely the key for it haha
can't sleep for seconds
the bot will go thru some perms check and also checking if the user is whitelisted etc etc so that will slow it down a bit
fair enough
thanks 👍
you didn't install the package, or installed it to different python version/venv
run pip3 freeze in console
uh, how did you install pycord then
command prompt, cmd, shell
?tag install
- Uninstall discord.py or any other forks of discord.py you might have with the namespace
discord.
python -m pip uninstall discord.py discord -y
2a. Install py-cord
python -m pip install py-cord
2b. Update py-cord
python pip install -U py-cord
Installing other builds:
Note: You need to have git installed. Use !git to find out how to install git.
Updating the module to Alpha (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord
yes
might have done pycord instead of py-cord
^
you installed wrong thing
use ```py
pip3 uninstall pycord
pip3 install py-cord
in cmd\
oui
je ne parle pas francais bien
yes
try now
Sup! Is there any way to convert commands.FlagConverter to dict?
Already tried that, but it returns Dict[str, Flag]. I need values with field types :C
field types?
idrk what FlagConverter's for but you can see the Flag attributes at https://docs.pycord.dev/en/master/ext/commands/api.html#discord.ext.commands.Flag
oh i see
kinda
Haha, I don't really know how to explain it. I need something like dataclasses.asdict()
can you give an example of what you're trying to achieve? might be easier to contextualise it
Suppose we have a car flags:
class Car(commands.FlagConverter):
name: str
price: float
color: str
# Assuming we initialized flags with message xd
car = Car('Test', 2500, 'Red')
data = await car.get_flags()
print(data)
It returns something like: {'name': Flag(...), 'price': Flag(...), 'color': Flag(...)}
And I am trying to find a way to convert it to: {'name': 'Test', 'price': 2500, 'color': 'Red'}
oh so you want to map it to the values they input
I think so xd
If there is no way to do that, I think it would be a good feature to pycord.
i think this page would be of better help https://docs.pycord.dev/en/master/ext/commands/commands.html#flagconverter
gives various examples of its usage
I've already checked that, I didn't find anything much, sadly...
how about
let's say you used data = await car.get_flags(), and data is {name: Flag}
you iterate through data and use car.getattr(name, None) so it defaults to None if it doesn't exist
oh i guess i gave wrong usage but
maybe like py mapping = {} for key in data: mapping[key] = getattr(car, key, None)which should result in py { "name": "Test", "price": 2500, "color": "Red" }
Oh, that's a good idea! Didn't think about that, lemme try
It does work, but when it comes to discord.Member we get __str__() xd
ah that's its string representation... hmm idk
This will work good with primitive types. I'll have to reinvent the wheel when working with discord.* types xd
well havefun
Maybe there is some nice way to convert these objects into string?
Sadly, Member.__str__() will return user nickname rather than id
could check the type beforehand and try to get another attr
ultimately you're just gonna have to do a ton of other processing for certain types
maybe not a ton but a bit more than others i guess
I think the best option will be creating a new class that inherits from FlagConverter with new method to properly handle discord classes.
go for it
most relevant discord classes in this context will have the id attribute so it'll be fairly straight forward
Yea, there are no options. Thank you for help ✌
allgood
Hello guys. How do I check the number of characters in a message?
For some reason I get some weird error saying I need to use _SpecialForm instead of str, pycord 2.1.0 I think is the version I'm using
How do i check if role is a bot role?
len function
thanks
Theres some attribute called is_managed or something like that
@full basin, how do i replace 10k with 10000 ?
is_bot_managed?
Eh, yes iirc
Okay thx :D
Have you tried something
?
no
i just want to know how i do to replace. I didn't ask you to code 😉
Then check some of the basic python functions and make an attempt 😉
I need to know what basic functions 😉
if role.is_bot_managed: is this correct or how do i use this XD
I think it's exactly that
Uhh. Don't know, does it return a boolean?
Omg im stupid thx xd
Yea ik i'm only tired XD
It's fine man, I'm trying to overcome something for hours by now xD which is this thing
Hey, can i get of user has nitro or not has nitro?
so i can not check this, okay, okay thanks
you also already asked this #1009513667353661661 message
yes but maybe you are wrong. I've also experienced it several times
no i am 100% sure you cant check if a user has nitro
But a sweepstakes bot can figure that out
so i think that
you can only do so if the user meets a certain number of factors like if the user has a banner or animated avatar
but even then they may not have any of that and still have nitro
mhmm okay
@slash_command(name='suggest', description='Suggest something for the bot')
async def suggest(self, ctx, suggestion):
f = open(“FelBotSuggestions.txt”, ‘w’)
f.write(suggestion)``` Why isnt this working? Im getting errors
( was not closed
Expected expression, although the brackets are closed?
?
async def on_message(self, message):
if message.author.id in self.afk:
await message.reply(embed=discord.Embed(description=f'**Welcome back,** {message.author.mention} **We have removed your afk**', colour=0x303135))
self.afk.remove(message.author.id)
try:
await message.author.edit(nick=message.author.name)
except:
pass
elif message.author.id in self.afk:
if message.author.mention in message:
await message.send('test embed')``` i tried this bot the ``
elif message.author.id in self.afk:`` line and under when someone is mentioned dose't work
The issue may be with a function above it
I got it fixed, Thanks though
Just bumping this again if anyone has any suggestions.
I just ran into the same issue, this time with an option int. It doesn't enforce input to be an integer and reads it in as a string
This is my function header:
async def dtt(self, ctx, team: str, player: str, odds: int, game_num: Option(int, default = 1), free_bet: Option(bool, default = False), account = Option(int, default = 1)):
# code
why cant i run the nomral commands and slash command together?
jarvis = commands.Bot(command_prefix="=", intents=intent, chunk_guilds_at_startup=False, help_command=None)```
intents are enabled also
i dont get any error or anything but when i try commands normaly with prefix it doesnt work but it does work applications wise
do you have message content intent
yes enabled
intent = discord.Intents(members=True, guilds=True, message_content=True)
and enabled in the dev portal?
yes
can you change it to this?
intent = discord.Intents.default()
intent.members=True
intent.guilds=True
intent.message_content=True```
ok a minute
it does work
what was the fix?
why pycharm dont work for pycord
you were missing the intents that are in default
lots of people use pycharm and it works great, what problem are you having?
i installed py-cord
but it says
that
"not found pakage discord"
when i have import discord
i have to install discord?
no, py-cord provides discord
how do I make view.wait() timeout=None ?
cuz the view timeout is None but the view.wait() stops waiting after some time
Code:
import mysql.connector
Traceback:
ModuleNotFoundError: No module named 'mysql'
mysql-connector-python==8.0.12 is shown in pip list.
@client.command()
async def meme(ctx):
api = "https://meme-api.herokuapp.com/gimme"
content = requests.get(api).content
data = json.loads(content)
#data = json.dumps(data, indent=4)
#print(data)
title = data["title"]
link = data["postLink"]
img = data["url"]
likes = data["ups"]
em = discord.Embed(description=f"[{title}]({link})", color=0x2F3136)
em.set_image(url=img)
em.set_footer(text=f"{likes}👍")
await ctx.reply(embed=em)
import discord, json, os, random, asyncio, string, time, hostingserver
from discord.ext import commands, tasks
from datetime import datetime
from hostingserver import keep_alive
import requests
your last option is broken
compare it to your other options
uninstall all discord related packages (py-cord, discord.py etc.) and reinstall py-cord
all good
pip uninstall i guess
@cyan quail
Hey i got a quick question. currently on my phone
can i check if any role permission is being changed? if yes then how?
because if im not wrong permissions returns a list.
so something like
if before.permissions != after.permissions would this check if the before perms is not the same as the after perm?
maybe on_guild_role_update? https://docs.pycord.dev/en/master/api.html#discord.on_guild_role_update
because the currently thing im doing is to check if 1 permission is being changed. if it is then set back
yes but permissions is a list
1 sec lemme get my laptop
well yeah
it'll compare the two lists
also on_guild_channel_update https://docs.pycord.dev/en/master/api.html#discord.on_guild_channel_update
its a pain without a mouse hahaaa
for channel permissions
Thanks for reminding me because i totally forgot to do that
even tho it is in the antinuke models
forgot about the invite too. Will do it in a bit
back to role thingy
So this is the current way im doing it. Which is not the best way to do that's why i was asking u
where you see it ?
@cyan quail if not before.permissions and after.permissions:
yeh forgot to change the code LOL
@cyan quail my internet is so bad that it wont even start the bot
currently at my grandma
that's not an atr error at all its just that is not loading the right way lol
maybe just relax until you're home lol
@cyan quail
nothing will get printed
ah nvm it works its just my internet bad
This works and it's a life saver lol
thanks nelo
How can i check-edit if a channel permission is being changed? I don't find it as a parameter for channel.edit
@bot.slash_command(guild_ids=[x])
async def addroles(ctx):
channel = bot.get_channel(channel_id)
message = await channel.fetch_message(message_id)
users = []
for x in message.reactions:
if x.emoji == "✅":
users.append(x.me.id)
for x in users:
x.remove_roles(ctx.guild.get_role(x))
x.add_roles(discord.utils.get(ctx.guild.get_role(x)))
await ctx.respond(f"Successfully replaced roles for {len(users)} users")```
is this code wrong?
discord.utils.get(ctx.guild.roles, id= or name=""])
It's overwrites
Then they aren’t different
Same error
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
x.add_roles(discord.utils.get(ctx.guild.roles, id=x))
They are lol
I think i have some knowledge in order to change a channel permission x)
for x in message.reactions: if x.emoji == "✅": users.append(x.author.id)
the error is here\
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'Reaction' object has no attribute 'author'
How can I fix this error? It's when having a status loop/cycle that changes every 13-15 seconds.
File "/home/container/main.py", line 105, in ch_pr
await client.change_presence(activity=discord.Activity(type=activity_type, name=name))
File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 1179, in change_presence
await self.ws.change_presence(activity=activity, status=status_str)
File "/home/container/.local/lib/python3.9/site-packages/discord/gateway.py", line 667, in change_presence
await self.send(sent)
File "/home/container/.local/lib/python3.9/site-packages/discord/gateway.py", line 627, in send
await self.socket.send_str(data)
File "/home/container/.local/lib/python3.9/site-packages/aiohttp/client_ws.py", line 150, in send_str
await self._writer.send(data, binary=False, compress=compress)
File "/home/container/.local/lib/python3.9/site-packages/aiohttp/http_websocket.py", line 687, in send
await self._send_frame(message, WSMsgType.TEXT, compress)
File "/home/container/.local/lib/python3.9/site-packages/aiohttp/http_websocket.py", line 598, in _send_frame
raise ConnectionResetError("Cannot write to closing transport")
ConnectionResetError: Cannot write to closing transport```
it works fine for me could be your wifi or something
@rare ice I think you are wrong about u said when u replied to my message because i added a few print statements before - in - after loop and that works perfectly fine, i also tried making other changes like channel rename and stuff
so it must be coming from the check if before.overwrites != after.overwrites
for x in message.reaction.users():
if x.emoji == "✅":
users.append(x.id)
i dont understand what im doing werong
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'Message' object has no attribute 'reaction'
It says in the error. Message has no attribute for reaction
uh so how do i get reaction?
I don't even know what you are trying to do honestly
im trying to replace a role
for each user who has already reacted to a message
role x changed to role y
?tag tryitandsee
I tried the code without the if statement and it worked.
But i can't figure out why the if statement won't work
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'ApplicationContext' object has no attribute 'remove_roles'
im so fucking confuse
Is there example of sub commands I couldn't see it in GitHub like other forks
@bot.slash_command(guild_ids=[x])
async def addroles(ctx):
channel = bot.get_channel(channel_id)
message = await channel.fetch_message(message_id)
reaction = message.reactions[0]
initial = discord.utils.get(ctx.guild.roles, id=x)
updated = discord.utils.get(ctx.guild.roles, id=x)
count = 0
async for user in reaction.users():
await user.remove_roles(initial)
await user.add_roles(updated)
count += 1
await ctx.respond(f"Successfully replaced roles for {count} users")```
this is my code
its adding roles to the wrong people now
I don't know man. its your code and you should know what it does, also i see that is a / command
yes
it's weird how u using ctx. I am using ctx: discord.ApplicationContext. What library are u using?
pycord?
yes
idk man
How can i check if a role is being added here to permissions?
i don't see any parameters for it in the docs
A code to get server's icon url
Ik but how can i fix it
no idea what youre trying by get.content
if you dont know what your own code does, nor do i
you use aiohttp
google how to use it
So aiohttp.get.content?
you use aiohttp as an async context manager
Normally it would use requests to get a meme from https://meme-api.herokuapp.com/gimme and put it in an embed and send once command is ran
But requests is a code blocker
# bad
r = requests.get('http://aws.random.cat/meow')
if r.status_code == 200:
js = r.json()
await channel.send(js['file'])
# good
async with aiohttp.ClientSession() as session:
async with session.get('http://aws.random.cat/meow') as r:
if r.status == 200:
js = await r.json()
await channel.send(js['file'])
just replace requests with this 👆
Isnt there anything easier
How can i check if a invite is being created to a certain channel?
Audit log in server settings
what about it is confusing
you can define a bot session if you subclass your bot
that will just remove one nesting
on_invite_create
event?
yes
wait
Yes
what
?
isn't it on channel update? lol
Why would it be on that
oh fuck alright
Invite has a channel attribute
async with self.bot.http_session.get(link) as r:
if r.status == 200:
return await r.json()
i have an http session defined in my bot
How can i check if any role is being added to the channel perms roles
thats about how short you can get
that one would be on_channel_update
Oh alright thanks
then check channel.permissions
nelo is none of those bruh listen 1 sec
not really
here where u can add a role. I don't see this in the params for channel lol
that's why i been asking around
because it's under channel.permissions
Called whenever a guild channel is updated. e.g. changed name, topic, permissions.
I know the event already bruh
Then what's the issue..?
you can also use permissions_for(...) if you need to check a specific object
i didn't see any parameters for channel perms
wdym
i was probably wrong about .permissions, that's for other objects with simpler permissions
but you're definitely looking for permissions_for()
yes because there's no atr for .permissions
like is not a channel param.
permissions for. lemme read it up
which is why im saying you should have just read further because permissions_for is also right there
how can i remove a role from the permissions?
use channel.set_permissions
👍
how do you make a slash command response private?
like so only the author can read it
ephemeral=True
in bot.slashcommand()?
is there a way to specify to discord that an ephemeral response is an error message so like it shows up red and stuff
ye
how
no
ok cool
at least not yet anyway
thank you discord very cool
also not salty about not being able to nest command groups
so im trying to get the discord mobile icon status on a discord bot
but its not showing up on it?
literally first google result
ik but im having trouble with it
hi, what are the actual objects stored in Guild.channels? i know it's a list, but is it of channel IDs or channel names?
GuildChannel objects
ohhhh, okay
so like, what would the syntax be for looking at the channel ID for one be?
Guild.channel[3].id or something?
3 being a random index number
What are you trying to do?
One message removed from a suspended account.
How would I convert :flag_bh: into an actual emoji using the api?
is uploading files in slash commands supported?
Does anyone have an idea on how I could get the custom emojis with the name butterfly and not the 🦋
yes
either the bot doesn't have use ext emoji permissions or the emoji was formatted wrong
looks like the latter, there's a missing >
thanks!
fixed it
my regex
How can i get invite link and link owner when member join?
Hi how do I get the guild id from on_member_join?
Ah thx.
the docs
link
rule 2 mate, use the internet https://docs.pycord.dev/en/stable/
I have problem with pycharm
hey sorry im using pycord after a bit off, for somereason my slash commands arent registering
from discord.ext import commands
from discord.ext import tasks
#from discord.ui import Button
import requests
from requests.structures import CaseInsensitiveDict
import json
import asyncio
import os
#from pycord_btns_menus import *
from datetime import datetime
from flask import Flask, jsonify, request
#API SETUP
client = commands.Bot(command_prefix="y.")
debug_guild = "998532010257690634"
owner_id = "901372249012051988"
@client.slash_command(guild_ids=debug_guild)
async def hello(ctx):
await ctx.respond("Hello!")
and then ofc token run, the bot runs and when i put an actiivty it displays it
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access and now this is throwing, but my token is correct and bot is running
i tried client cmd, same thing
commands.Bot
you have to important discord.ext
u have to enable the scope in the dev portal
guild_ids have to be a list of ints, not a string
same with the owner_id
unless you cast it already in your code when you retrieve it, but best practice to leave it in int
is there a faster way to mass remove role from users?
I use for loop and that's slow so I was wondering if there's another way and a better practice
hey! in my project which pings me everytime a new product is , i use syncwebhook(url).send to send embeds in a discord channel. I'm trying to attach a button with the link of the product under each embed sent, so i tried to add a view element but as my code isn't in an async, i get "no running loop". Is there an equivalent of view() without it needing to have an "await"?
I'm trying to achieve something like
webhook = SyncWebhook.from_url(webhookurl)
embed=discord.Embed(title="blablah", color=0x78c5f2)
webhook.send(embed=embed, view=view)
that would attach the button defined in view under my embed
how can isend an message in an on message event in a specific channel (not the channel where the message is from)
get the current user roles
remove the ones you want to remove
then do await member.edit(roles=roles)
in the event you get the channel from cache and send the message there
to send messages you have to await it, View is not async
i've never really worked with await and async, just dived into it and pycord for this project, so how could i trigger my await to run if it's in a loop, without slash command?
async def mass_removing(
ctx: discord.ApplicationContext,
role: discord.Option(discord.Role, required=True)
):
await ctx.defer()
Number_Members = len(role.members)
for member in role.members:
await member.remove_roles(role)
await ctx.respond(f"{role.mention} has been removed from {Number_Members} users")
that's how it was before, I'll try to do what u said above 👍
does hosting like from 2 device harm the bot?, i tried to use my main bot to debug my code about intents and i cant use any slashcommands that have been registered
I'm trying to remove a view from a message after 5 minutes but for some reason this doesn't work.
with save_image_data("image", rendered) as file:
msg = await ctx.respond(file=file, view=view)
async def timer():
await asyncio.sleep(60 * 5)
try:
await msg.edit(view=None)
except:
pass
task = self.bot.loop.create_task(timer())
await task
The view is still there after 5 minutes. With text commands this worked fine but now it's not working and I'm not sure why
so um, i am using apscheduler for some work, it works fine when the jobs are stored in memory, but when i use sql/mongodb for storing jobs(for presistence), it gives this error:
uptime is a function with comands.command() decorater, if i remove the uptime block, error will move on to the next prefixed command, idk whats happening, i am lost
try using view timeouts for that instead of creating your own. https://docs.pycord.dev/en/master/api.html#discord.ui.View.on_timeout
omg this makes it much easier
ye
A bit old but might have some useful info
https://stackoverflow.com/questions/1412787/picklingerror-cant-pickle-class-decimal-decimal-its-not-the-same-object
im not subclassing discord.ui.View, so would i just do something like this instead
view = discord.ui.View()
view.on_timeout = lambda: ...
nvm its async
but still
view.on_timeout part is right, i have never used lambda so not sure about that
Ye u cant do async lambda's so it wont work anyway
Why is there no error stack raised whenever a cog fails to load?
One of my cogs is failing to load, and I've no idea why, no traceback in console, it tries loading and then just nothing happens and it doesnt load
add store=False to the load_extension
Thanks
@celest lichen Please don't cross post in your own thread and in here.
sorry - made the thread bc this felt too long. i'll delete the stuff here
Somebody tell me, is Bridge playing up ....again or is it just me.
Pycharm is giving me this error, plus Bridge commands aren't being loaded in cogs.
The First issue I fixed easily, You need to pip uninstall py-cord ( the one from the github page ) because it has the type SpecialForm thing and then download the one from pypi page or pip install py-cord
The second issue It's the same as mine I'm trying to figure out why it's happening and how I can actually load the bridge commands because it's strange xD
@bridge.bridge_command(name="Config", description="First Initialization setup", guild_ids=[0])
async def _config(self, ctx: bridge.BridgeContext):
# Private bot, channels are gathered from the first guild that pops up.
channels = {int(channel.id): channel for channel in self.client.guilds[0].channels}
if os.getenv("WAIT_CHANNEL") == "0":
view = View()
view.add_item(SelectManager(placeHolder="Choose a waiting channel", options=channels))
view.add_item(SelectManager(placeHolder="Choose the Aaron Channel", options=channels))
await ctx.reply(content="Activating first setup initialization\n"
"Please follow the instructions bellow: ", view=view)
This is a command I have in a cog file ( the cog file is configured how the docs said it should be ) and it doesn't load, if anyone knows what to do let me know!
Hello! I have a little issue perhaphs someone can help me, i think thaht i'm using the basic discord.py. This is my code:
@bot.command(name = "cat")
async def cat(ctx):
user = (f'{ctx.author.display_name}')
codi_usuari = usuari [0:5]
channel = discord.utils.get(ctx.guild.channels, name= codi_usuari +"log")
messages = await channel.channel.history(limit=100).flatten()
print(messages) ```
And i get this error
```messages = await channel.channel.history(limit=100).flatten()
AttributeError: 'TextChannel' object has no attribute 'channel'```
What i need is to get all the messages from a specific channel that changes with the 5 first characters of the user. Does anyone know how to solve this?
The error is because you're trying to get an attribute which doesn't exist because the utils is already getting the same channel
So instead of typing channel.channel just type channel
oh 🤦♀️ thanks!
how can I restart the bot automatically, like once a day?
there's a command I think it's bot.restart or smth
And then you can do a loop that activates one a day I guess
bot.stop and then bot.start
When you do bot.stop and then afterwards bot.start it doesn't really close the program itself
I think
try stuff with the os module
oh well
Yeah the docs is the best tool
now will tasks work after the bot is turned off 🤔
you can kill the bot process with the os module and run it again
That's an option aswell
im gonna go with both
You close the connection with discord not the program itself
Whenever you do client.close I assume it'll continue where you did client.run
Here kind of
Yeah after you close the connection it'll continue from client.run, another thing you can do is when you close a connection it'll trigger the event when you close connection with discord
The one from the GitHub is corrupt?!
I think so
It worked for me but now if I try to register bridge commands it doesn't work
The First issue I fixed easily, You need to pip uninstall py-cord ( the one from the github page ) because it has the type SpecialForm thing and then download the one from pypi page or pip install py-cord
Waa-?! So your saying their GitHub-build is broken? Great...
I doubt the github build is broken
did you download py-cord-2.0.1.tar.gz? you just need to extract it first
I used pip
yes I get that
How do i disable a /slash Command complete so that the command is not shown for anyone without administrator permissions?
No it's that
use the @discord.commands.default_permissions(ban_members=True) decorator
I do this git+https://github.com/Pycord-Development/pycord.git#egg=py-cord but either way it should work
Did you test it?
not recently
although master is considered "alpha" and could break at any time
if you're having issues you can pin to a specific commit
IDK when it worked man :/
why not just use stable?
Same as the pypi page
what?
The package on the pypi website is the same as the stable version
It won't register bridge commands
can you create a github issue with a minimal working example?
I tried here first to check if I'm the only one because then I would just spam a spammed issue
well, first, can you make a new thread in #969574202413838426 and send your code
Yeah sure
@ionic snow Thanks! My bots fixed now, weird the GitHub version isn't working
NP
Yes but those who don't have permissions will see the /slash command anyway
I want that the command is not show up yk?
no they won't
it hides the command from anyone without that permission
@prisma flicker Posted
Oh rly? Ok thank u :D
is there a way other than integration, that it shows up the command on a certain channel?
So I got the fix for this issue, if you load it in an extension then do store=False
Yup, my bot already does store=False (can't actually remember why), but eh, all works now, no need to complain :)
Same as me xDDDD
what permission does a bot need to do permission checks on users running commands? does it need manage roles?
no permissions
my commands dont load
uhm nothing gets printed
even tho the bot is ready
the extension also gets loaded
anyone got any idea why my emoji only function is acting like it's toggled to on in every channel? lol
it should be
getting called on every message,
performing an sql select for the channel id of the message sent,
then if the emoji only toggle is set to true,
run the check to see if the message contains any text,
and if it does delete it
but it appears to be skipping steps 2 and 3 lol
by the way i acknowledge this is probably an extremely slow-running implementation of this feature but i'm still quite new to python lol
^^^ anyone?
how many ram would i need for a simple bot that will only be in 1 server
less than 100MB. my current discord bot only uses like probably 50MB on prod
thanks for the info!
How do I make it so the response to slash command is something only that user can see?
ephemeral
start using an async database
cuz its blocking otherwise
is there one you'd recommend?
which one were you using
psycopg2
use asyncpg
is this important? lol idk much abt github i just see red and think bad
thanks
if you install the stable version you'll be ok
it should just be pip install asyncpg
thank you!
as far as usage is it mostly just putting await infront of my SQL commands?
yes
or you can use it as a context manager
like async with _ as _:
so it can automatically close the connection
or a cursor
In https://github.com/Pycord-Development/pycord/blob/master/examples/views/persistent.py, it says:
It is recommended that the custom_id be sufficiently unique to
prevent conflicts with other buttons the bot sends.
Does this mean that the view may conflict with other instances of the same persistent view if I create the persistent view multiple times for multiple users? Do I have to create a seperate custom_id for the buttons for each user? Ping on reply please
is there a reason to use bot by subclassing the client class compared to regular usage ?
You can use it to override events
what's the difference compared to bot.event decorator ?
There's probably better reasons that I'm not aware of though
Sorry, I'm not completely sure of that
The custom id should be unique at least within your code
If you have multiple instances of the same view they can share the same id
Alright, so its pretty much just to prevent the bot from getting confused which button should handle the callback when the user interacts with it?
I guess so
Ok thanks
if you have a large scale bot its not gonna work with a single custom id
How come?
now that i think about it, it shouldn't have any issues
Alright
say you have a feature where you can create your own self role select menus, and each select menu has a "self_role" custom id, since there's gonna be different select menus for different roles, its not gonna be all the same
but then again the role can be passed in to a view/select subclass and there wouldn't be a need for that
Oh so pretty much where users are able to set up the view you'll have issues?
Since they'll actually be different views
ill have to test on my own to see if two different views can have the same id and if they can be added to persistent views
Ok
can i set footer on embed initialisation ?
no
regrettable, thanks
How can I get the id of a slash command?
?
you get the command and then you access its id attribute
how can I get the command?
thx
does the id change after some time?
don't think so? im not sure what happens if you update the parameters
you'll have to try out for yourself
what's the best approach to slash commands that are supposed to send in chat, instead of being replies to the user ?
send two messages and delete the reply after a second ?
just make the response be ephemeral and send the message afterwards
thanks
and one more thing, suppose i have a db with several entries, each being id of a guild, inside of each are ids of channels with some sort of info inside it; if i want to ensure for messages to be send to correct channels, i would want to use discord.Client.get_channel(id-of-channel).send(content="message")
am i right ?
should be
?tag tias
fair
Does Member.pending take the guild member verification level into account or just the member screening?
still trying to figure out the solution to this weird problem if anyone knows
just screening from what i can tell
okay, for some reason my sql query is returning the isEmojiOnly column as a tuple ????
its type is boolean - i thought type conversion was automatic
how do i make it return the actual boolean value?
how do you access tuple items
i seem to have fixed it by using if isemoji[0] but that feels like a kind of a bodge
does it always return a tuple, even if it's only selecting one value?
fetchone always returns a tuple
Sql libs are going to return tuples
thank you, i mustve missed that when i was reading the docs
because it gets the entire row
or it wasnt mentioned
And since it's a tuple with 1 element it's always truthy
so like
it gets the whole row but then filters it to just the column you selected
?
why don't you just
print the result
and see what happens
would be significantly easier to troubleshoot
i was doing that - i've solved the problem. just trying to understand how it works better so i can avoid it in future lol
voila
it'd probably help to read the docs for whatever library you're using too
fetchone is similar across most i'd assume but it'll at least explain what's happening
ah yep, i see that now im looking over the docs again. i think my eyes just sort of glazed over it haha
asyncpg is important for the postgres driver. It's the current driver I use on my prod bots for postgres
yeah, i'm swapping things over to asyncpg now that i have all my queries working
i was just worried abt the Tests Failing thing
it's normal to see that, since it's just the commit pushed on their dev branch, and that happens all of the time
oh wow, asyncpg doesn't have a connection and a cursor, it's just all connection
that means im changing more than i thought i'd be lol
oh jesus, do i need to wrap almost my entire main.py in an async function?
idk i didnt make the code
is it ok to put change presence in on_ready, it will update every 5 seconds
i have a while loop running
button.disabled = True
button.label = f"You must wait {self.combat.turn_skill - self.combat.turn} turns."
await interaction.response.edit_message(view = self)
button.disabled = False
button.label = f"Skill"
await interaction.response.edit_message(view = self)
can i do something like this without the double interaction
i guess it was 5 in 10 seconds
i alr did read this
after investigation of an hour
seems apscheduler first serializes all staticmethod functions
due to command.command() decorator, serialization is not possible and pickle throws error, any way to fix this?
i can't edit message with select menu. i've got this error
In components.0.components.0.options.0.emoji.name: Invalid emoji, but i see this emoji
how can i fix it?
is there a way to use @ tasks with times so like 4pm and so on?
pass a list of datetime.time objects into the time parameter https://docs.pycord.dev/en/master/ext/tasks/#discord.ext.tasks.loop
what did you enter for the emoji?
emoji from server
Traceback (most recent call last):
File "/Volumes/Danya disk/coding/Py-cord/HFD/venv/lib/python3.10/site-packages/discord/ui/view.py", line 375, in _scheduled_task
await item.callback(interaction)
File "/Volumes/Danya disk/coding/Py-cord/HFD/hfd/ui/SettingsMenu.py", line 30, in select_callback
await interaction.response.edit_message(embed=embed.automod(interaction.user), view=AutoModMain(interaction.client))
File "/Volumes/Danya disk/coding/Py-cord/HFD/venv/lib/python3.10/site-packages/discord/interactions.py", line 840, in edit_message
await self._locked_response(
File "/Volumes/Danya disk/coding/Py-cord/HFD/venv/lib/python3.10/site-packages/discord/interactions.py", line 959, in _locked_response
await coro
File "/Volumes/Danya disk/coding/Py-cord/HFD/venv/lib/python3.10/site-packages/discord/webhook/async_.py", line 213, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In components.0.components.0.options.0.emoji.name: Invalid emoji
full error + emoji
im asking what did YOU input into the select menu code for the emoji
you likely need at least name:id or <name:id>
:AutoMod:
that's your issue
i understand
there isn't bot on this server
can i implement checks at the context menu command level so that it doesn't execute the function if the check fails ?
checking it with this and the command still works
no exceptions, no nothing
nice to know thanks!
it should be a list of checks, not check
reinstall py-cord and make sure it's latest (2.0.1)
as in check = [chk] ?
also note you can use the existing check decorators from ext.commands
checks=[chk]
ty
so you can pass in as many as you want
pycord or py-cord
py-cord if you're using pip
are you sure your bot is running on the correct python installation
yup
show the full error from your first screenshot
do you have dpy installed by any chance
yes
yes
?tag install
- Uninstall discord.py or any other forks of discord.py you might have with the namespace
discord.
python -m pip uninstall discord.py discord -y
2a. Install py-cord
python -m pip install py-cord
2b. Update py-cord
python pip install -U py-cord
Installing other builds:
Note: You need to have git installed. Use !git to find out how to install git.
Updating the module to Alpha (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord
these are two different python installations
and also, discord.Bot doesn't have prefixed commands
i don't have any error's, but i can use any of
?tag client
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
.
command's don't load
@simple canopy
because you are using wrong bot class
read this
but im not using prefix commands
make sure you have applications.commands scope enabled
ok
this is still changing but global slash commands can take a while to load (it's meant to be instant now but this doesn't seem to be consistent)
they were instant for me in past 2 months~
i suppose i meant "consistent across applications"
fair
try waiting a bit
also, you can specify guild_ids=[] for command, so it will be instant for your testing guild
without
I'm trying to create a decorator that checks if the message upon which the context menu is being executed belongs to the bot, but i can't find the way to get the message object from the context. am i missing something ?
@simple canopy
||kurwa||
could you show whole code (if its not big)
xd
are you from poland?
import discord
bot = discord.Bot()
@bot.event
async def on_connect():
print(f' ')
print(f'Zaladowano discorda (Connected)')
print(f' ')
@bot.event
async def on_ready():
print(f' ')
print(f'Jestem gotowy do uzycia!')
print(f' ')
await bot.get_channel(996907722949804133).send(embed=discord.Embed(title='Success',
description='Poprawnie zaladowano discorda!',
color=0x55FF55))
@bot.slash_command(name='botinfo', description='Informacje o bocie!', guild_ids=[965780715985838101])
async def botinfo(ctx):
await ctx.respond(embed=discord.Embed(title=f'AlienBot - Informacje', description=f'**Status:**\n\n> ・Py-Cord - *pycordversion*\n> ・UpTime - *uptime*\n> ・Ping - *ping*\n\n **Statystyki:**\n\n> ・Serwery - *{len(self.bot.guilds)}*\n> ・Użytkownicy - *{len(self.bot.users)}*\n> ・Owner - *Aruuvi#9667*\n> ・Komendy: *{len(self.bot.commads)}*'))
@bot.slash_command()
async def test(ctx):
await ctx.respond(content=f'test command')
bot.run('token')```
no, i'm from Ukraine
yes, i'm here, you can stop pinging every 2 seconds
ok, sorry xd
are you sure bot have access to channel you are running commands in?
also, be sure to, also, add bot scope
do u need intents?
try adding intents=discord.Intents.default()
ok
and intents=intents in bot instance
you need both of these btw
ok
💀
this, yea?
yes
Hmmmmm
still not working...
invite url problem maybe?
Nah
try restarting discord
¯_(ツ)_/¯
may be you just don't see / commands, but they are here
re-add your token
does your bot send the embed that is in on_ready
yes

commands.Bot is for prefixed commands
idk if that makes a difference
it doesn't
i used commands.Bot for slash commands too
{len(self.bot.guilds)}
you're not in class
so when i do
@tasks.loop(time=time(hour=8))
async def my_task(self):
...
it gets executed every morning at 8 o'clock?
you don't have self
💀
you can't use self. outside class
this one should've been registered then, actually 
yes delete it
still
update your pycord to 2.1
yes
so I copied your code and everything worked when I changed bot = discord.Bot() to bot = commands.Bot()
try to do the same
discord.ext.commands.Bot
from discord.ext import commands
or that
you forgot ext
yea
ok
i changed something
and it works now
but commands still dont load
i deleted discord.commands
and just commands.Bot
did you scoll through all commands?
scoll?
in discord
yes
i see you have alot of them
it should yeah
and you can make it a list for multiple times
Nelo please help me
show your full code
import discord
from discord.ext import commands
intents=discord.Intents.default()
bot = commands.Bot(intents=intents)
@bot.event
async def on_connect():
print(f' ')
print(f'Zaladowano discorda (Connected)')
print(f' ')
@bot.event
async def on_ready():
print(f' ')
print(f'Jestem gotowy do uzycia!')
print(f' ')
await bot.get_channel(996907722949804133).send(embed=discord.Embed(title='Success',
description='Poprawnie zaladowano discorda!',
color=0x55FF55))
@bot.slash_command(name='botinfo', description='Informacje o bocie!', guild_ids=[965780715985838101])
async def botinfo(ctx):
await ctx.respond(embed=discord.Embed(title=f'AlienBot - Informacje', description=f'**Status:**\n\n> ・Py-Cord - *pycordversion*\n> ・UpTime - *uptime*\n> ・Ping - *ping*\n\n **Statystyki:**\n\n> ・Serwery - *{len(bot.guilds)}*\n> ・Użytkownicy - *{len(bot.users)}*\n> ・Owner - *Aruuvi#9667*\n> ・Komendy: *{len(bot.commands)}*'))
@bot.slash_command()
async def test(ctx):
await ctx.respond(content=f'test command')
bot.run('token')```
so i should delete on_connect
yes
define datetime at on_ready() and then subtract it from datetime.now
is time utc or local?
defaults to utc, but it supports timezone
...timezone MIGHT be broken though
last i checked was a few months ago, if it is i may give a go at fixing it
i dont find any timezone arg
https://docs.python.org/3/library/datetime.html#time-objects
broken only certain parts, doesn't update timezones that change example for UK, winter changes to GMT summer BST, it doesn't do that, you'll have to use the etc/UTC something like that
i recall it used to raise an error for tzinfo, but i'd personally just stick to using utc anyway
hey does anyone know how to add that like little checkmark on the selection menus for the selected option? is it an emoji or something else
it's for select menus with multiple options
thanks
and if u want it just for 1 option can u just set it to max 1 min 1?
Yeah, but its set to that by default
well then how can u get the checkmarks there with only being able to select 1 option
min value = 0 and max = 1?
I'm not sure if you can get checkmarks if there's only one option
How can I fix this error? It's when having a status loop/cycle that changes every 13-15 seconds.
File "/home/container/main.py", line 105, in ch_pr
await client.change_presence(activity=discord.Activity(type=activity_type, name=name))
File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 1179, in change_presence
await self.ws.change_presence(activity=activity, status=status_str)
File "/home/container/.local/lib/python3.9/site-packages/discord/gateway.py", line 667, in change_presence
await self.send(sent)
File "/home/container/.local/lib/python3.9/site-packages/discord/gateway.py", line 627, in send
await self.socket.send_str(data)
File "/home/container/.local/lib/python3.9/site-packages/aiohttp/client_ws.py", line 150, in send_str
await self._writer.send(data, binary=False, compress=compress)
File "/home/container/.local/lib/python3.9/site-packages/aiohttp/http_websocket.py", line 687, in send
await self._send_frame(message, WSMsgType.TEXT, compress)
File "/home/container/.local/lib/python3.9/site-packages/aiohttp/http_websocket.py", line 598, in _send_frame
raise ConnectionResetError("Cannot write to closing transport")
ConnectionResetError: Cannot write to closing transport```
what would generally be the best approach to handling has_permission check ? simply adding the decorator raises the exception, i'm not sure what's the best method to add a (.respond) would be
subclassing and replacing the error ? not quite sure how to use try/except around decorator next to command definition
handle it in on_command_error
doesn't seem to react. is that applicable to context menu error handling ?
yeah i need on_application_command_error. thanks anyway
yes
same way you do checks with every other command
oh that's an old message
damn it discord
How can i edit the guild community to true/false. Community its inside the guild features
anyone knows how to add a created_at as timestamp to embed? its not working for some reason i did ctx.message.created_at
Hey guys, on_guild_join doesn't work at all for me at all
do I need any intents for that
You need members intents for that iirc
discord.utils.utcnow()
await guild.edit(community=True or False)```
Nelo there's a problem
go on
there's no mention about rules_channel, public_updates_channel in the docs
is it possible to set them as default?
No but like
on the ui you have to specify them
so you have to do the same on the api
it won't let me enable community if i don't mention those channels lol
so do just that
it literally says
community (bool) – Whether the guild should be a Community guild. If set to True, both rules_channel and public_updates_channel parameters are required.
