import discord
from discord.ext import commands
intents = discord.Intents()
intents.message_content = True
bot = commands.Bot(command_prefix='!',intents=intents)
@bot.event
async def on_ready():
print(f"{bot.user} is ready and online!")
@bot.command()
async def hello(ctx):
await ctx.reply("Hey!")
from config import TOKEN
bot.run(TOKEN)
#General Help
1 messages · Page 6 of 1
oof
❤️ you man!
anybody know how to keep spaces in an embed?
kinda annoyed that discord just chops off extra spacing 😐
all the solutions that google spouts out don't work either lmao
does embed work different to a normal message?
i can get all those spaces in a normal message
yes, I've solved the issue i had now though
discord's embed chops off all unnecessary spaces
so any space beyond just one will be removed
I've tried implementing page extension module of pycord, but it's not working for me.. certainly missing something
how can i implement this :/
https://docs.pycord.dev/en/master/ext/pages/index.html
ahhh
ok
what should i do after importing all the class data baronkobama?
used \u1CBC to do it
theres examples for paginators
GitHub
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/paginator.py at master · Pycord-Development/pycord
OH MY GOD !! thanks
this code uses SlashCommandGroup .. can you please link a repo or something which uses prefixes.. because this is not working for me.. I'm sending you the code:
I copy-pasted the code with a intents, prefix and bot definition:
Code -
@commands.command()
async def rr(self, ctx:commands.Context, message_id, emoji, role):
await ctx.reply(f'{message_id}, {emoji}, {role}')
message = self.client.get_message(message_id)
await message.add_reaction(emoji)
Error -
Ignoring exception in command rr:
Traceback (most recent call last):
File "C:\Python\lib\site-packages\discord\ext\commands\core.py", line 181, in wrapped
ret = await coro(*args, **kwargs)
File "e:\Python\Evelynn Workspace\Evelynn4.0 RE\cogs\reactroles_cog.py", line 49, in rr
message = self.client.get_message(message_id)
AttributeError: 'Bot' object has no attribute 'get_message'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Python\lib\site-packages\discord\ext\commands\bot.py", line 360, in invoke
await ctx.command.invoke(ctx)
File "C:\Python\lib\site-packages\discord\ext\commands\core.py", line 927, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Python\lib\site-packages\discord\ext\commands\core.py", line 190, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'get_message'
idk whats the issue
as the error says, Bot object does not have something called get_message it suppose to be TextChannel.get_message
how do i get a TextChannel object?
Hi, every single bot I used pycord on, just suddenly stopped working.....like, the bot goes online but doesn't respond to any prefix commands....tho,slash commands do work....
I've been trying to fix this for a while now and haven't found why suddenly all bots just became an empty shell...any help would really be appreciated....
No error pops up on the terminal too
I am also getting this error, my guess is that this is somehow connected to what's happening....
If so, how to solve it?
get guild,
guild.get_channel,
channel.get_message

i have got the same error in discord.py but it doent freeze my commands or my bot
Can anybody provide me a sample code for ext-pages, paginator.. I'm a beginner and having trouble implementing https://raw.githubusercontent.com/Pycord-Development/pycord/master/examples/views/paginator.py
@stable tiger pls can you?
arigatou (thanks)
I HAVE FIXED!
Hey how i can say time in Modal? i have tried so: time=self.children[0].value (in async def callback(self, interaction: discord.Interaction, time=self.children[0].value):).
the callback is not provided any other params other than interaction
How i can then say the time?
what do you mean?
also this self.children[0].value wouldnt work in a function def as a parameter
So i mean i have a Command with time so this how i can say the time ?
so the time is inputted into the first field of the modal?
simply access self.children[0].value in the function then
Yeah but how i can say the time? I must in callback or?
in the function
not in the parameter section
in the function where you have all the code
Yeah wait
class Giveaway_Basic(discord.ui.Modal):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.add_item(discord.ui.InputText(label="⏰ Wann soll das Gewinnspiel enden?",
placeholder="Beispiel: 5d", required=True, min_length=2))
self.add_item(discord.ui.InputText(label="🎁 Was gibt es zu gewinnen?",
placeholder="Beispiel: Discord Nitro", required=True))
async def callback(self, interaction: discord.Interaction, time=None):
time_give = {"d": 86400, "h": 3600, "m": 60, "s": 1}
hmm = time.split(" ")
mydate = self.children[0].value
for i in hmm:
mydate += int(i[:-1]) * time_give[i[-1]]
timestamp = (datetime.datetime.now() + datetime.timedelta(seconds=mydate)).timestamp()
timestamps = int(round(timestamp))
await interaction.response.send_message(f"{self.children[1].value}")
await asyncio.sleep(mydate)
await interaction.response.send_message(f"yay")
So? i have this self.children[0].value to the mydate = self.children[0].value made.
that works
also you cant call interaction.response twice for an interaction
if you need to send a follow up use interaction.followup
Ignoring exception in modal <extensions.Giveaway.Giveaway_Basic object at 0x000002004FD9FF10>:
Traceback (most recent call last):
File "C:\Users\zReaxrYT\PycharmProjects\Discord\venv\lib\site-packages\discord\ui\modal.py", line 217, in dispatch
await value.callback(interaction)
File "C:\Users\zReaxrYT\PycharmProjects\Discord\extensions\Giveaway.py", line 24, in callback
hmm = time.split(" ")
AttributeError: 'NoneType' object has no attribute 'split'
why do you still have that parameter in there?
what do you mean with parameter?
how is a parameter ?
time=None this is useless
so then is time.split(" ") not working
you want to call it on mydate
and when i delete time=None then is this time_give = {"d": 86400, "h": 3600, "m": 60, "s": 1} not working
that has nothing to do with that parameter
Ignoring exception in modal <extensions.Giveaway.Giveaway_Basic object at 0x00000250CDE8FEB0>:
Traceback (most recent call last):
File "C:\Users\zReaxrYT\PycharmProjects\Discord\venv\lib\site-packages\discord\ui\modal.py", line 217, in dispatch
await value.callback(interaction)
File "C:\Users\zReaxrYT\PycharmProjects\Discord\extensions\Giveaway.py", line 24, in callback
time_give = {"d": 86400, "h": 3600, "m": 60, "s": 1}
NameError: name 'time' is not defined
can someone help me, pls?
If I want to put every member in my server into an embed, what should i do?
for name in ctx.author.guild.members:
members = name
value=f"Member No: {ctx.author.guild.member_count}\nMembers: {members}",
plz help me thx
all_member = []
for name in ctx.author.guild.members:
all_member.append(name)
embed = discord.Embed()
embed.add_field(name = "..." , value = f"Member No:{ctx.author.guild.member_count}\nMembers: {", ".join(all_member)}"
thxx
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'list' object has no attribute 'join'
what shall i change?
oh sorry
edited
try this again
@plush lintel
ok
@stray smelt ```py
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: sequence item 0: expected str instance, Member found
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)
Can u try simple debug by print(ctx.author.guilds.members) ?
this appends Member objects into the list, i hope you knew that already
Oh mb
cant send empheral messages via ctx.respond?
await ctx.respond('❌ This command can be used By Teachers only !', ephemeral=True)
what issue are you running into?
no issue
it isnt showing empheral tho
are you deferring the interaction with ephemeral=True?
yes
see
show me the entire command callback
there is no error tbh
if assignment_image == None: await ctx.respond(f':white_check_mark: Feedback Send Successfully to {student.name}', ephemeral=True)
the entire command
its a very big command
i mean normaly if i send it should work
does it take alot of time to process through that you have to defer the interaction?
yes
i have done that
then show me that part
show me the defer line
thats responding, not deferring
oh i see the defer line up there
add ephemeral=True into its args
@silver arrow
Is there any way for me to get the current page input , the user is currently on?
or maybe user selects a page .. and i can get that somehow
Hey, how can I check if a datetime format is spelled correctly in an if statement? For example, if 10 was specified in a command, the command doesn't know what 10 means, days, hours, minutes, seconds, etc., how can I throw an error?
I don't know how to call the full format in the if query.
time_give = {"d": 86400, "h": 3600, "m": 60, "s": 1}
Check if it ends with d, h, m, s
how?
if d == None:
or what?
Heh? Slash commands or normal ones
Slash Command and Modal
Can i see your command function
yeah
parameters
async def callback(self, interaction: discord.Interaction):
time = self.children[0].value
time_give = {"d": 86400, "h": 3600, "m": 60, "s": 1}
time_spilt = time.split(" ")
mydate = 0
for i in time_spilt:
mydate += int(i[:-1]) * time_give[i[-1]]
timestamp = (datetime.datetime.now() + datetime.timedelta(seconds=mydate)).timestamp()
timestamps = int(round(timestamp))
await interaction.response.send_message(f"{self.children[1].value} - <t:{timestamps}:R>")
so time is a string
what do you mean?
Are you getting time like this? 10h15d
for what?
How do you take input
I tried checking the docs but is there a way to send a message to a specific channel(via using channel id)?
not sure if i looked enough
Yes
i want only a if query not more when a user a failed datetime format used then a just a error message
guild.get_channel(id).send(...)
Thank you!
as far as a i remember u get the guild via
ctx.guild
do you know what i mean? @sour terrace ?
No i dont
😦
First how do you get time and in what format
i know how i can a if querry but i dont know how i can a datetime format define.
Idk what you are trying to do
You said that to me I just want to know how it works?
hey tri-tan, do you have any idea on how i can get the input that user has clicked on the next page in a paginator
There is something calles endswith in python google it@slender lintel
Lemme check docs of sec
I have Google used 🤨
I want to implement something like: user chooses a specific page, but for that i must know which page the user currently is in.
If i can get the input of user clicking the next button.. I can make a variable to get the current page
Usually the paginator starts with page 1
there is a attribute called current_page.. i tried printing that.. turns out to be 0 at beginning
can i add reactions to a message that is invoked with slash commands?
but can i get the current_page whenever user clicks on next page?
Ig that cuz of the list of the pages or embeds that you put so it gives positions of the page according to its position in list so it gives 0
?tag tias
how do i make a command that replies to the original command?
it says interaction has no attr add_reaction
oh yes ig. But i still didn't get the solution : (
how can i get the input of user clicking the page buttons
paginator.interaction_check()
I have never used this but you can try and tell me too
Where are you trying to add reaction lmao
ctx.reply(...)
its not my code.. it was code sent by another person.. and in the docs i couldnt find add_reaction
when you send a response you can add reaction to that message
this was sent by him; https://paste.pythondiscord.com/lowiyelovu.py
does that reference the original message used for the command?
i can suggest them to do so
Yep
whenever I run the code it tells me there is an error in "elif choice1 == '2' or choice == 'two':
could anyone help? (mention me if you can help ) thx
identation? is your tab button dead? 🙂
sorry I didn't understand
what do you mean?
the part after elif should be indented.. pretty basic stuff my friend.
I'm sorry english is not my native language
🙌 📔 🇬🇧
nope didn't work
Why are you adding : after elif
😴
How to solve it
ur using pycord i am using d.py
so i dont know
like it doesnt freeze the bot in d.py
try to resync commands manually
just install from github
in server settings
Ok
how to check how many members have in a role
on_interaction
role.members should return a list iirc
do you have an example?
ty
Nvm, there's on_application_command
https://docs.pycord.dev/en/master/api.html#discord.on_application_command
@bot.slash_command(guild_ids=tbw)
async def check(ctx, role : discord.Role):
await ctx.respond(role.members)
if role.members < 10:
await ctx.respond("< 10")
else:
await ctx.respond(">= 10")
yo
this does not work
i think its because if role.members < 10:
the "<" does not have its meaning in python
can someone help mee
i really need an example lol
help
youre not comparing the element count
but how do i fix it?
len()
wat
basic python
just toss it in that function
hi o/ what's the maximum amount of channels a discord server can have? is there a way to query it from a bot?
i hate knowing pycord but not knowing basic python
what does the list contain?
dcria = ctx.guild.get_role(975412724102234163)
owner_dcria = ctx.guild.get_role(975412867044098139)
embed=discord.Embed(title=None, description="Member added to your clan", color=discord.Color.green())
if owner_dcria in ctx.author.roles:
if len(dcria.members) < 9:
await membro.add_roles(dcria)
await ctx.respond(embed=embed)
else:
await ctx.respond("Your clan already have 8 members, no one can be added anymore", ephemeral=True)
else:
await ctx.respond("Your clan is not registered", ephemeral=True)
i've got the command workin
but it does not satisfact the if
swap it to be greater than max members here
um
dcria = ctx.guild.get_role(975412724102234163)
owner_dcria = ctx.guild.get_role(975412867044098139)
embed=discord.Embed(title=None, description="Member added to your clan", color=discord.Color.green())
if owner_dcria in ctx.author.roles:
if len(dcria.members) > 7:
await ctx.respond("Your clan already have 8 members, no one can be added anymore", ephemeral=True)
else:
await membro.add_roles(dcria)
await ctx.respond(embed=embed)
else:
await ctx.respond("Your clan is not registered", ephemeral=True)
like this?
yes
k
did not work
it just ignores the if
i added 5 members to that role
even with a limit of 3 (just for testing)
it doesnt
if its going to the if statement then the condition is evaluated
have you tried inspecting the contents of the list yet?
Is it possible to check if a member's dms are open without trying to message them?
@keen oasis
user.dm_channel.can_send() returns a bool
replace user with a discord.Member object
nice name btw
class SettingsManagerCog(commands.Cog):
def __init__(
self, bot: commands.bot, settings_manager: SettingsManager
) -> None:
self.bot = bot
self.settings_manager = settings_manager
self.setting_names = list(
self.settings_manager.defaults.__dataclass_fields__.keys()
)
@slash_command()
async def update_settings(
self,
ctx,
setting: discord.Option(
str,
description="Setting name to update",
required=True,
choices=list(self.setting_names)
),
is there a way to make this boilerplate work? i have a SettingsManager cog which the user provides a settings model to, then initializes this cog with the SettingsManager. I have a generic update_settings command but it needs access to a self property in the choices kwarg for discord.Option
I just randomly started getting discord.errors.HTTPException: 405 Method Not Allowed (error code: 0): 405: Method Not Allowed, how can I figure out what method is causing it?
Am already running b7*
upgrade to master for the fix but this exception is "feel free to ignore" in b7
Uploading messages from the database
I have a database. How do I load. Messages with buttons.And also how to delete this message?
Is there anyway that I can defer() an interaction as ephemeral, then followup the interaction with a non-ephemeral message?
No
L
How can I delete the defer() loading message
How to delete a message by id, or how to get message by id?
get_message if in cache fetch_message otherwise then message.delete()
How do I pass mes Id?
py-cord 2.0.0b5
Not sure if this works like this. You could send the message without a View and then edit the message to add the view
then the id would work too
does anyone know if you can select multiple items in a pycord dropdown menu?
Yes you can.
i'm having a problem getting server display names...i just re-added my bot as admin in case i was missing perms and all of name, display_name, and nick are showing up as my normal username and not my server name...
Are you getting the user object or member object?
a mix, depending on if it's a bot message or not
i am pulling via message.author
Well only works with member
doesn't work on member either
Huh can you send code?
def get_nick(member):
if hasattr(member, "nick") and member.nick is not None:
return member.nick
else:
return member.name
Guild intent?
Or member intent?
Other than that I have no idea then sorry
Code looks fine to me
there's a builtin attribute on member for this, display_name
i'm trying to dm a user a file. i have the file path, my main problem is i need the File object. how do i get this? open() gives me an IOBufferWrapper which doesnt work.
f = max(glob.glob("logs/naenaraplus_*.log"),key=os.path.getctime)
await usr.send(discord.File(open(f,"rb"),filename=f))``` like this?/
no
literally just give the filename as a string to discord.File
and then send it with the file kwarg
so kust discord.File(f)
just*
yeah
hey there!!, i want to upload an image file to discord and get its image url, how to achieve that
what are the styles for discord.utils.format_dt?
Hi what's wrong?
you don't need to fetch message just
await interaction.response.edit_message("edited")
How do I delete it?
is there an example of subclassing a bot?
class MyBot(commands.Bot):
def __init__(self):
super().__init__(command_prefix="prefix here",
intents = discord.Intents())
bot = MyBot()
@bot.event
async def on_ready():
print("test")
you don't need to subclass bot for slash command
import discord
bot = discord.Bot()
@bot.slash_command()
async def hello(ctx, name: str = None):
name = name or ctx.author.name
await ctx.respond(f"Hello {name}!")
bot.run("token")
just do something like this then it should work
aight
well I'm considering that im adding common features
so shoving the internal stuff would be more organised
how do i get the local user time?
i tried using discord.utils.utcnow() but that isnt my time, but if i use that in a embed i get my local time
its not your local time for a reason
you should generally work with utc as a timezone without messing around with timezone conversions
why are you attempting to do such a thing?
just use pm2
if youre running it on a server that is
what are the alternatives to "load_extension"?
whats that?
you can make it run anything, not just node.js stuff
is load_extension broken?
whenever I load a cog using that method
for some reason commands are not appearing in application
I tried it using th example
show code?
the cogs as well
this is the cog I am attempting to load
"record"
I made a post here in forums and no1 respond
Intents?
what class are you subclassing here?
this does not answer my question
I mean the on_ready function
wym
are you subclassing discord.Bot or commands.Bot?
commands.Bot
voilá, found the root issue
command = prefixed command, slash_command = application command
did something have broken commands.Bot?
your cog contains prefixed commands
except that youre using groups so that doesnt make sense
shit
You can use commands.Bot for both
well record.py is already grouped
let me see if I switch from commands.Bot to discord.Bot
see if it makes a difference
nope still the same issue
I checked if the commands exist
only the main commands I see
no subcommands
Hello guys,
I want to use a callback on my button so I can use it dynamically
I found that you have to use py-cord for that
So i try to see how ti work and it completely broke my bot the commands are not recognized anymore
Can some one tell me what I am doing wrong with this quick code who is not working please
give your bot message and message_content intents
both of those are required for prefixed commands to function with api v10
Do you have a quick sample please ?
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)
there
Thanks !
how would I go about unregistering commands? I've removed some commands from my code and they've not unregistered on Discord.
Hi, I have trouble with the commands like @client.command(). Python dosent see it
Import discord
from discord.ext import commands does nothing
But @client.event works
yes, cuz u probably did client = discord.Client()
Yep
yeah...
What should I write instead?
discord.Client() is used for events only
Oh
if you want commands, you have to use commands.Bot, but please make the instance bot, instead of client
Thanks!
np!
Hello, the way my slash commands are written is giving an error....
class BotName(commands.Bot):
def __init__(self):
super().__init__(command_prefix=get_prefixes)
@self.slash_command(guild_ids=dc_servers,description="Show's the bot's latency.... :robot:")
async def ping(ctx):
await ctx.respond(f":ping_pong: **Pong !** `{round(self.latency * 1000)}` ms")
This is the error.....
discord.errors.ClientException: Callback for ping command is missing "context" parameter.
is there something wrong with it?
Because your ping command is in a class the first parameter should be self so ctx is being set to self and thus there is no. parameter for context. adding self to before ctx in the ping defenition would fix this
I did that but now it shows
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: ping() missing 1 required positional argument: 'ctx'
your ping command looks like this?
async def ping(self, ctx):?
and still gives this error
Does this happen if you don't put the command in your bot class?
Lemme try
Hi, i'd like to add my bot to the server to test it with more people but i don't know if one of its features from is allowed here
It has a feature that if you reply any messages from him, it answers you
It doesn't responds any messages that are not direct replies to its messages, only when clicking on them and pressing "reply"
and it also responds non-reply messages with its @
it's a chatbot like feature
is this allowed on the server? i'm confused because it's not a prefix but it's a way to call the bot like a prefix does
No it doesn't, the command works fine when its outside the class
I think a @ (mention) counts as a prefix. If you DM dorukyum he would tell you if you could.
I'm not exactly sure why that happens. Is there a specific reason why you want it in the bot class? I dont think it is an intend way to make commands.
No no specific reason, just created that class to keep my code organized...if it doesn't work, its okay
Okay, thanks ^^
Yeah, the class is for subclasses features of the bot. You should look into cogs to keep your code organized.
Does slash commands work with cogs?
Cogs, often known as modules or extensions, are used to organize commands into groups. This is useful
Yes
Hi again, what should I write instead here? Sry im new to bot coding
import discord
from discord.ext import commands
from datetime import datetime
import random
intents = discord.Intents.default()
intents.messages=True
TOKEN = *nope*
client = discord.Client(intents = intents)
[...]
@client.command(aliases = ['!Бэбэй'])
async def on_message(message,question):
rep = 412547573367308288
Bebchoice = ["Да","Нет","Возможно","Пошёл"]
await rep.send(f"Бэбэй говорит {random.choice(Bebchoice)}")
client.run(TOKEN)
I dont really understand what should I replace
Hello,
Quick question
I use call back on button
I display a Embed that i stock on a List[]
I would like to click on next and update my cursor "pos" every time i click on next or prev
so i can access the list elem of the pos
How can i make this code work please ?
so you see the client = discord.Client?
yes
what do you want to do - message prefixes or slash commands?
prefix
what is ur bot gonna be?
like what type
because no point in making message prefix based commands if you don't get the message intent
is a logging bot
- some fun commands
Here is the full code
import discord
from discord.ext import commands
from datetime import datetime
import random
intents = discord.Intents.default()
intents.messages=True
TOKEN = nope
client = discord.Client(intents = intents)
@client.event
async def on_ready():
print("Я Маления, клинок {0.user}".format(client))
@client.event
async def on_message(message):
username = str(message.author).split("#")[0]
user_message = str(message.content)
channel = str(message.channel.name)
beb = 0
cha = client.get_channel(975441449560723556)
if message.author == client.user:
return
else:
embed = discord.Embed(title = f'Сообщение от : {message.author}\n', description = f'Содержание : {message.content}\n Автор : {message.author.mention}\n в канале {message.channel.mention}',timestamp = datetime.now(), color = discord.Colour.blue())
await cha.send(embed = embed)
print(f"от {username} в {channel} - {user_message}")
if message.channel.name == ':speech_balloon:флудильня':
if user_message.lower() == "Вызов Малении".lower():
await message.channel.send(f"Я Маления, клинок Микеллы")
return
if message.channel.name == ':speech_balloon:флудильня':
if user_message.lower() == "Вызов Бэбэя".lower():
while beb != 100:
beb = beb + 20
await message.channel.send(f"*Подключение {beb}%*")
if beb == 100 :
await message.channel.send(f"**Бэбэй на связи**")
beb = 0
if message.channel.name == ':speech_balloon:флудильня':
if user_message.lower() == "Бот, кому ты служишь?".lower():
await message.channel.send(f"Я служу Бекону")
@client.event
async def on_message_delete(message):
chs = client.get_channel(975441449560723556)
if message.author == client.user:
return
else:
embed = discord.Embed(title = f'Удалено сообщение от : {message.author}\n', description = f'Содержание : {message.content}\n Автор : {message.author.mention}\n в канале {message.channel.mention}',timestamp = datetime.now(), color = discord.Colour.red())
await chs.send(embed = embed)
@client.command(aliases = ['!Бэбэй'])
async def on_message(message,question):
rep = 412547573367308288
Bebchoice = ["Да","Нет","Возможно","Пошёл нахуй"]
await rep.send(f"Бэбэй говорит {random.choice(Bebchoice)}")
client.run(TOKEN)```
Hey guys!
I hope this is not a stupid question.
If my bot "discord.AutoShardedBot", are "@tasks.loop" executed multiple times?
I don't understand the shard system yet 🥸
The idea is to make a 8ball command, i have message intent on (for logging).
This is a multi func. bot
I mean if your bot will have message logging, then discord may give you the message intent, but still it will take a long time so I recommend using slash cmds
Switched client to bot = commands.bot(command_prefix = "-")
Gives an error
Exception has occurred: TypeError
'module' object is not callable
File "C:\Users\ragna\DiscordLogBot.py", line 11, in <module>
bot = commands.bot(command_prefix = "-")
Bot has to be uppercase
the first letter
It works, now I need to change @client to @bot.event
I have another one
Exception has occurred: TypeError
Aliases of a command must be a list or a tuple of strings.
File "C:\Users\ragna\DiscordLogBot.py", line 65, in <module>
async def eigtball():
code :
l65 async def eigtball():
rep = 412547573367308288
Bebchoice = ["Да","Нет","Возможно","Пошёл нахуй"]
await rep.send(f"Бэбэй говорит {random.choice(Bebchoice)}")
@worthy basin @steep lark get_message not work
#help-rules 4, and the message probably isn't cached
I'm sorry.I've been sitting with this for 2 days now.This is for booting after restart.
You can try fetch_message as well ;
But overall maybe problem is in self.bot being None
I don’t think view has bot attribute, does it ? Then do you provide it for that subclass
Well anyway people would get bot/client instance from interaction.client
It works. But it is very strange that he could not find the message without channel
Ok, so I fixed the @bot problem but my 8ball code dosent seem to work, bot just ignores it.

define the command function with something else, not an event name, that will be very confusing, name it something like "eightball"
also, you need ctx arg in the function
and in order to send a message, the rep needs to be a discord.Channel or discord.Member or discord.User object
hey there!!, i want to upload an image file to discord and get its image url, how to achieve that
.
1 sec
are you going to send the image and get the link in the same function?
well it doesn't really matter.
what you need to do is get the instance of the message, then get the message attachments (discord.Message.attachments) and you will get a list. Then you can use the url function on the attachment from the list and you will get the link
still ignoring
idk
no dude
so just send the mesage, obtain its id, fetch message and get attachment url?
are you going to send the message in the same channel as you executed the command?
yes
nono, if you will get the link in the same command/event that you sent the message, then you can just get the message instance :)
then you don't need the discord.Channel = ..., you just do ctx.send(...)
eloborate more?
ok, let's say you send the message ctx.send(...), you can get the instance of that with msg = ctx.send(...) and msg will be the discord.Message so you don't need to make unnecessary API calls to get the message
and you won't need to fetch the msg
oh
still ignores
any errors?
bro, have patience, this question was originally posted 5 hrs ago
show the command code please
prefix - bot = commands.Bot(command_prefix = "-")
command - ```@bot.command(aliases =['bebey','Bebey'])
async def bebeyball(ctx):
Bebchoice = ["Да","Нет","Возможно","Пошёл нахуй"]
await ctx.send(f"Бэбэй говорит {random.choice(Bebchoice)}")```
hm
could it be because of the discord update
wait
@crimson coral can you use message prefixed cmds if you don't have the msg intent and your bot isn't verified?
What would I put in the isinstance() func for an error when the user doesn't have a specific role needed to use the command
idk the error type
yes, if your unverified
bot is not in 100 servers
discord.ext.commands.MissingRole
or commands.MissingRole
(for short ^)
Thank you!
Guess I need to wait... Thank you very much for your help! ❤️
👍
Maybe / command?
Is it possible to have a "project-level" pip install? I have two projects with conflicting package requirements
virtual environments are your friends
if you need a quick and easy way to just get a venv with its own dependencies, consider looking into pipenv
note: this isnt necessary if you are using pycharm, it handles venvs for you already
ty
Now for something else ...
I just installed the current master, and I get TypeError: issubclass() arg 1 must be a class when loading my cogs.
Example:
class AdminCog(BaseCog):
Where BaseCog is a subclass of commands.Cog
Hello,
Quick question
I use call back on button
I display a Embed that i stock on a List[]
I would like to click on next and update my cursor "pos" every time i click on next or prev
so i can access the list elem of the pos
How can i make this code work please ?
Quick question, how to check if somebody has a specific role?
like if message.author == (role):
if role in message.author.roles
Traceback (most recent call last):
File "/home/nex/PycharmProjects/spanner-v2/venv/lib/python3.10/site-packages/discord/cog.py", line 715, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "/home/nex/PycharmProjects/spanner-v2/src/cogs/official/debug.py", line 24, in <module>
class Debug(commands.Cog):
File "/home/nex/PycharmProjects/spanner-v2/src/cogs/official/debug.py", line 80, in Debug
async def clean_bot_message(self, ctx: discord.ApplicationContext, max_search: int = 1000):
File "/home/nex/PycharmProjects/spanner-v2/venv/lib/python3.10/site-packages/discord/commands/core.py", line 1580, in decorator
return cls(func, **attrs)
File "/home/nex/PycharmProjects/spanner-v2/venv/lib/python3.10/site-packages/discord/commands/core.py", line 644, in __init__
self.options: List[Option] = self._parse_options(params)
File "/home/nex/PycharmProjects/spanner-v2/venv/lib/python3.10/site-packages/discord/commands/core.py", line 696, in _parse_options
elif issubclass(p_obj.default, (DiscordEnum, Enum)):
TypeError: issubclass() arg 1 must be a class
Is this a me problem? I'm on the master branch, literally just updated
seems to error on any argument with a default value that isn't in a discord.Option
async def foo(..., x: discord.Option(int, default=100)): # works
async def foo(..., x: int = 100): # doesn't work
this is about to be fixed
awesome
trust me to install a commit that's broken and think I broke something since its working in production 💀
@tropic fractal hey I just merged the fix so could you reinstall and check if it works now?
I can confirm it's working on my end
if role in ctx.author.roles:
thankx
Sorry for the late reply, it is working now
great thanks
Hey all. Been fighting a TypeError error for a while now and I think I'm doing something simple wrong haha
The case;
I fetch a channel using sales_channel = sales_guild.get_channel(int('channel_id_here')) where sales_channel is fetched by running sales_guild = self.get_guild(int('guild_id_here')). In my variable explorer I see the right guild and right channel get fetched. Now whenever I run await sales_channel.send(embed) with a configured Embed, I run into the following error: TypeError: object TextChannel can't be used in 'await' expression. Though when removing await, it says sales_channel.send(embed) was never awaited. Any insights where I'm going wrong?
It seems to error out specifically at File "%AppData%\Local\Programs\Python\Python310\lib\site-packages\discord\abc.py", line 1428, in send channel = await self._get_channel().
you need to await the sales_channel instance's definition
Hey, I got a question. I think the Intents in my script isnt working. Is there anything wrong with that? In discord.py it works.
why do i get this error?
Not understanding what you're saying specifically. Mind providing an example?
sales_channel = await sales_guild.get_channel(...)
.set_footer(text="...") ig
You have to define, that the text you wrote is the text arg
Cheers. I shall try that right now.
ahh
🥂
Ran sales_channel = await sales_guild.get_channel(int('channel_id')) and it results in the same
TypeError: object TextChannel can't be used in 'await' expression 🤔
Right. That's how I have it set up, but it gives me the TypeError when I await channel.send but says it needs to be awaited (as I expected) when I leave out the await.
I'm thinking either my channel definition isn't correct or something's off 😄
Let me drop the entire traceback
try to fetch the channel with bot.get_channel
maybe this works idk
I'm parsing the bot as the self, but let me check
Since I'm using cogs. Does that make sense or am I going wrong there?
It runs into the same issue.
Traceback (most recent call last):
File "%AppData%\Local\Programs\Python\Python310\lib\site-packages\discord\ext\tasks\__init__.py", line 176, in _loop
await self.coro(*args, **kwargs)
File "d:\Tech\Avenged Sevenfold\discord\bot\bot.py", line 79, in on_ready
await OpenSeaCog.update_sales.start(self._bot)
File "%AppData%\Local\Programs\Python\Python310\lib\site-packages\discord\ext\tasks\__init__.py", line 205, in _loop
raise exc
File "%AppData%\Local\Programs\Python\Python310\lib\site-packages\discord\ext\tasks\__init__.py", line 176, in _loop
await self.coro(*args, **kwargs)
File "d:\Tech\Avenged Sevenfold\discord\bot\cogs\opensea.py", line 358, in update_sales
await sales_channel.send(embed)
File "%AppData%\Local\Programs\Python\Python310\lib\site-packages\discord\abc.py", line 1428, in send
channel = await self._get_channel()
TypeError: object TextChannel can't be used in 'await' expression
That's the traceback
Also embed=embed
If the command is inside a cog, it has to be self.bot
Tried that after your recommendation earlier and no success still, unfortunately.
To confirm, I do see the guild and channel get fetched properly. I'm just unable to send the embed.
Hm
Greatly appreciate your time and effort btw. Just wanted to get that out there.
Yes, I shall
Ok
@tasks.loop(seconds=request_interval)
async def update_sales(self):
init_timestamp = int(time.time())-7200
last_timestamp = None
sales_guild = self.get_guild(int('guild_id'))
print(sales_guild) # < This populates without issue
sales_channel = sales_guild.get_channel(int('channel_id'))
print(sales_channel) # < This populates without issue
event_timestamp = last_timestamp if not last_timestamp == None else init_timestamp
url = f"https://api.opensea.io/api/v1/events?only_opensea={os_only}&asset_contract_address={asset_contract_address}&event_type=successful&occurred_after={event_timestamp}"
last_timestamp = int(time.time())
logging.info(f"Fetching data from URL: {url}")
assets = requests.get(url, headers=headers).json()
for asset in assets.get('asset_events', {}):
sale_event = OpenSeaEvent(asset)
embed = Embed(
title= f"{sale_event.name} just sold for {sale_event.total_price} ETH",
url= sale_event.permalink,
timestamp= datetime.utcnow())
embed.set_image(url=sale_event.image_url)
embed.add_field(name="Name", value=sale_event.name, inline=True)
buyer_value = f"[{sale_event.buyer_name}]({sale_event.buyer_address})" if sale_event.buyer_name != None else f"[{self.shorten_address(sale_event.buyer_address)}]({sale_event.buyer_address})"
seller_value = f"[{sale_event.seller_name}]({sale_event.seller_address})" if sale_event.seller_name != None else f"[{self.shorten_address(sale_event.seller_address)}]({sale_event.seller_address})"
embed.add_field(name="Buyer", value=buyer_value, inline=True)
embed.add_field(name="Seller", value=seller_value, inline=True)
logging.info("Sending embed to channel.")
await sales_channel.send(embed=embed)
await asyncio.sleep(request_interval - ((time.time() - init_timestamp) % request_interval))
Yes, it is.
Hm, try to send something else other than an embed, like a normal string
If it works, then we will know it's something wrong with the embed
Alright, I shall try. Thanks.
Happy to help!
Still the same issue unfortunately. Tried just sending a test message but no success.
Hm
How about trying to get the channel with self.get_channel(id)?
Instead of getting the guild and then channel
Running master branch
Should I try 2.0.0b7?
Give it a try ig
hey friends. is it possible to get an interaction after sending a view with ctx.followup.send?
should be fixed in the latest master
Sweet. Let me grab.
a view's components can always trigger an interaction regardless of the method used to send it (send, respond etc), so long as you have means of handling it
ideally you're using the callbacks to handle them
generally that's what I do - but I'm trying to call edit_original_message after disabling the view components, and for that I figured it needs to be done in the context of an interaction
uhhh
followup.send returns a WebhookMessage if im not mistaken, so you should build around that
could you elaborate or point me to a reading source to better understand? 🙏
hold on
So as per https://docs.pycord.dev/en/master/api.html#discord.Interaction.followup, interaction.followup is Webhook object, and https://docs.pycord.dev/en/master/api.html#discord.Webhook.send Webhook.send returns WebhookMessage. For most cases, you can assume WebhookMessage is more or less identical to Message, and you can read about its own methods at https://docs.pycord.dev/en/master/api.html#discord.WebhookMessage
oh hold on, if it's a webhook message can't I just edit it directly after modifying the components?
yeah pretty much
thanks for the elaborate answer!! :):)
all good
And so it did. Thank you! And a big thank you to @surreal nimbus 🙌
why dont coming a error?
time_regex = re.compile(r"(?:(\d{1,5})(h|s|m|d))+?")
time_dict = {"h": 3600, "s": 1, "m": 60, "d": 86400}
def convert(argument):
args = argument.lower()
matches = re.findall(time_regex, args)
time = 0
for key, value in matches:
try:
time += time_dict[value] * float(key)
except KeyError:
raise commands.BadArgument(
f"{value} ist eine falsche Zeitangabe! Nutze: `h|m|s|d`"
)
except ValueError:
raise commands.BadArgument(f"{key} ist keine Zahl!!")
return round(time)
how do i make a button just clickable to a certain person?
and send a message just for a person who is not the author of the command
hey for slash command options, what's it called to have a menu where I can select a user? something like /blah <menu to select a user>
found it, it was discord.User
how do i make that one message "the bot is thinking"?
can someone help me with my python discord bot it wont respond to me when use the prefixed command
pls
override interaction_check in your view
ctx.defer()
you need message content intent
what is that im new as heck
why is this happening?
as of apiv10 message content is now a privileged intent and must be requested:
#library-updates message
You took too long to respond iirc.
what?
@hearty rain
Hello, I am trying to import from discord.ext bridge using pycord, but it keeps telling me that it cant access it. I installed pycord, and am using vscode
Install latest beta version or just from git master ;
I did a py -3 -m install -U py-cord install
Can you have multiple prefixes?
👍
Yes
How o.o
well, that's not right
!install
Install pycord:
pip uninstall discord.py
pip install py-cord
Install pycord beta:
pip uninstall discord.py
pip install py-cord==2.0.0b7
Install pycord alpha from git:
pip uninstall discord.py
pip install git+https://github.com/Pycord-Development/pycord
you need beta or alpha
Just pass in a tuple of prefixes in command_prefix
hey what's a simple way to take another input from a user after the user clicks a button?
class MyButton(Button):
def __init__(self,label):
super().__init__(label=label, style=discord.ButtonStyle.primary)
async def callback(self, interaction):
await interaction.response.edit_message(content="**Anime selected!**" , view=None)
episode_fun(self.label)
await interaction.followup.send("**_Select_ Episode _from:_ 1-"+ str(total_ep)+'**')
class MyView(View):
def __init__(self,n):
super().__init__()
for i in range(1,(n+1)):
button = MyButton(str(i))
self.add_item(button)
@bot.event
async def on_ready():
print(f"{bot.user} is ready and online!")
@bot.command()
async def weeb(ctx):
anime_fun(ctx.message.content)
pages = []
for i in range(len(anime_posters)):
pages.append(discord.Embed(title=anime_titles[i],description=anime_desc[i]))
pages[i].set_image(url=anime_posters[i])
paginator = Paginator(pages=pages,timeout=180.0, author_check=True, disable_on_timeout=True)
await paginator.send(ctx=ctx)
view = MyView(len(anime_posters))
await ctx.send("Select Anime: ",view=view)
so after the callback, ie. followup.send(), I want a user input
why is role.edit just not working? await role.edit(name='new name') just blocks the code and does not show any error?
I am sure im not suppressing any errors and that role is valid
Im also sure it isnt a permission issue
could you show ur code?
@role_group.command(guild_ids=[961950658595020850])
async def edit(self, ctx: discord.ApplicationContext, name: Option(str, 'The name for your role.')) -> None:
role = ctx.author.roles[-1]
print(role) # outputs the role so it is valid
await role.edit(name=name)
await ctx.respond('Role updated.')
it just blocks on role.edit
what does print(role) printed?
the name of the role
could you show me?
but if i put type(role) it says discord.Role
ok
what perms your bot has? and is the bot's role higher than the specific role?
the bot has admin and has the highest role
are there any error raised?
if I remember correctly I had this issue before and it magically fixed itself but now it has returned
cog_command_error doesnt output anything and I cant really put a try and except block since the code blocks at role.edit
try removing this and try doing this:
try:
#edit the role
except:
raise```
yeah try it and remove -> None
the role did not edit?
nope
weird
yeah im properly confused
have you perhaps considered the fact that the role could have the exact same name its being edited to?
I remember I was last time but then it suddenly started working again
I put a different name each time
what version of pycord?
master
your error handling could blocked the error from raising, may i look at your error handler?
I removed it already
you have on_command_error / on_error in your code in whereever place?
also
try:
await role.edit(name=ename)
print('yay')
except:
raise
it never prints yay
nope
very weird....
right, did you enabled it?
could i be i need presence intent
idk in which way that would make sense
lets try
discord.Intents.all()
make your life easier :)
true
still nothing 😦
i changed the code to this
@slash_command(guild_ids=[961950658595020850])
async def test(self, ctx: discord.ApplicationContext):
await ctx.author.roles[-1].edit(name='test')
await ctx.respond('Success')
yeah
how much?
two
ok
the lowest one is far below the bot
try this:py role = ctx.author.roles[1] #edit your role here
dont do [0] cuz is @ everyone role
still nothing
try instead getting the role and edit it maybe
b!rtfm Guild.get_role
I couldn't find a documentation with the name guild.get_role! Maybe you used to command wrong? Correct Usage: <prefix>rtfm <docs> [<term>] (eg. b!rtfm py cool)
List of Documentations you can search:
python
pycord
discord.py
yarsaw
nextcord
disnake
b!rtfm pyc guild.get_role
Best matches for guild.get_role in pyc
yeah thats how i initially got the role
and update pycord
i just reinstalled pycord
alright
ive never opened an issue before lol
oh there is actually an issue about it
25 days ago
and he also said it magically started working again just like it did with me
could be an issue on discords side?
oh i almost forgot i have exams in an hour
ill check back later if it works
thanks a ton for the help btw
Thats what worked on my system using powershell 🙂 The issue was that I had discord.py installed, and didnt know I had to uninstall that before starting with pycord. I went through and looked at the docs and found the solution
Can someone help me?
is there in Pycord sth like interaction.deferResponse? I want to tell my command users they have to wait a bit
It’s just ctx.defer()
but can I sent a custom Message? Like "MyBot is thinking"?
ctx.defer() trigger this but you can send stuff yourself with channel send or something before responding to interaction
do i just use @commands.cooldown(1, 10, commands.BucketType.user) for slash commands cooldowns?
i believe is discord.commands.cooldown. dont mess up with ext.commands and discord.commands
i am not sure tho
alright thanks also about the permission for slash commands, if I apply multiple permissions together are the permissions optional? example: if I applied administrator and manage_messages to a slash command. And if a user with administrator will they be able to run the command? or do thy need both of the perms
cuz it had been a long time i look at pycord's slash commands
cant seem to find discord.commands.cooldown in the docs..
yeah same
examples/cooldown.py line 7
# an application command with cooldown```
you mean default_permissions decorator?
alright
yeap
ah so the user needs all the permission stated?
wow the option for slash commands changed it wasn't like this before lol
lol
mhm
how do i check if a user is currently timed out?
how i can install the version from github
!install
Install pycord:
pip uninstall discord.py
pip install py-cord
Install pycord beta:
pip uninstall discord.py
pip install py-cord==2.0.0b7
Install pycord alpha from git:
pip uninstall discord.py
pip install git+https://github.com/Pycord-Development/pycord
how do i check if a user is currently timed out?
or is there no way to do so? :((
b!rtfm pyc Member.is_time
No results found when searching for Member.is_time in pyc
cant find it in docs..
b!rtfm pyc Member.timeed_out
No results found when searching for Member.timeed_out in pyc
Best matches for Member.timed_out in pyc
there ya go
ah tysm
np
I've already done but I always get this message
class Ticketclose(discord.ui.Button):
AttributeError: module 'discord' has no attribute 'ui'
reinstall
you using replit?
ok then just reinstall and restart ur terminal&IDE (code editor)
pip uninstall py-cord -y
pip install -U git+https://blablabla.iamlazytotype
pip list and send the output here
restart ur terminal first
Package Version
aiohttp 3.8.1
aiosignal 1.2.0
async-timeout 4.0.2
attrs 21.4.0
charset-normalizer 2.0.12
frozenlist 1.3.0
idna 3.3
multidict 6.0.2
pip 22.1
py-cord 2.0.0b7
setuptools 58.1.0
yarl 1.7.2
restart ur computer and try again it should work then
gtg
How I can use ctx with an edit statement to edit the last message
Hey, I've made a bot. thing is, if two ppl concurrently use the bot.. it messes up the results for the first user and shows the results for the latter
any solutions guys?
will it be fixed with multithreading?'
Hello, I have made a bot using commands.Bot with pycord......
For some reason, only slash commands are working....when prefix commands are typed, no response from bot and no error on terminal too.....
cogs get loaded (which has the prefix commands) , but no response
You most likely have some blocking code
#library-updates message
ohh, forgive me 
how to install a git branch through requirements.txt
git+https://github.com/Pycord-Development/pycord
pymongo
motor
asyncio``` i hope this is right
code
@bot.slash_command(guild_ids = [925595902956171285, 963260514379657286],description= "Shows the avatar of the mentioned user")
async def avatar(ctx, user:Option(discord.Member)):
embed = discord.Embed(title=f"Avatar of {user.mention}", color = discord.User.color())
embed.set_thumbnail(url = discord.User.avatar_url)
embed.set_footer(text=f"Requested by {ctx.author}", icon_url=ctx.author.avatar_url)
await ctx.respond(embed = embed)
error
Application Command raised an exception: TypeError: 'property' object is not callable
full traceback show the line where the error is being raised
File "C:\Users\%USER%\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 128, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'property' object is not callable
send it like this , this one shows the line where the error is popped up
Traceback (most recent call last):
File "C:\Users\%USER%\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1098, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\%USER%\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 331, in invoke
await injected(ctx)
File "C:\Users\%USER%\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 128, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'property' object is not callable
uff u didnt get me ig
Send the full traceback
BRUH
Do you know the difference between a class and an instance?
In other words, you should use user instead of discord.User
ohhhh let me try
i did but this
dude...

Learn the difference between an instance and a class
that gets you stable, you need beta/alpha to get any of the new features
ok i'll for now tell me what the problem is 
yh
tenks broo i learned and solved the problem too u helped me so much

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'tuple' object is not callable
Anyone getting the same error when using slash commands with discord.TextChannel option?
lmao dude is j trying to help you in the long run, you're gonna struggle if you don't learn these things
update to github master, it's fixed there
oh ok
What is this error all about?
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In _errors: [{'code': 'APPLICATION_COMMAND_TOO_LARGE', 'message': 'Command exceeds maximum size (4000)'}]
Is there a way to track/get a list of users who clicked a button? then use it to get a random user like a giveaway command
i think u can check the people that reacted make a list or just pick their names and use random to choose one
use callback and define some sort of variable in db, increase the variable by 1 in callback function
kk
Is it possible to edit an embed and keep the reactions that were initially on it?
i want any admin panel for my bot, any api alr present for this? like accessing command usage per guild; its chart, bot stats, in a website
I think so
any idea how to do that? unsure if im doing something wrong but when i use edit on the embed it gets rid of all the reactions that were there.
Idk
But why reactions?
Buttons exist
they do. working on a giveaway bot and reactions seem to work easier for that but if im missing something im alright with switching
Idk, it shouldn't remove the reactions when editing
hmm alright ill have to take a look again, thought that was my issue
ahh yes youre right thanks.. dumb move but had small error
What type of error? You accidentally cleared the reactions again?
no, was just being stupid, still had the code in for deleting and sending a new embed after editing it..
Ty, I figured it out last night tho. I downloaded the development version as I uninstalled discord.py
Hi! Does anyone have any idea why this event isn't being called? All the other events work but not this one
@bot.event
async def on_thread_create(thread):
print("Thread Created")
What pycord version? I think this is only in beta
How do I make my slash commands only appear in specific channels?
how do i get the voice channel version of pycord?
anyone knows?
Im on 2.0
how can i display an avatar even if the user doesn't have one?
when you install use py-cord[voice]
The amount of options or something related to your command object is too large, send your command code
I keep getting this error when i start my bot
How do I solve this??
I dont think theres any issue tbh, this just feels like a warning, my bot is working fine, and it gets updated normally(the slash commands get synced)
but how do I get rid of that msg??
thanks in advance :D
And yes, i invited the bot with applications.commands
im on 2.0.0b7
version
update to newer version/master
I have a function in a cog file, that i need to call with data from another file thats not apart of the bot.
Problem is, it has self. And using @staticmethod doesnt work as in the function in the bot file i need to use client.
How can I call the function without self?
my command has a lot of options how much is the max?
The default_permissions will only apply when the bot gets added to the guild right?
So basically it will not mess up current configured permissions that are already set
by administrators?
asyncio.run(crispAPI.crisp_chat_received(channel_name=channel_name, raw_data=data))
I'm using slash command and was wondering if there's a way to change interaction failed message to something else in SlashCommands
Are you responding to the slash command?
Instead of this
I want it to fail but instead of telling everyone it'll reply as something else
Instead of The app did not respond to something like bot failed to join
Yeah but will only the person who sent the command see this?
As a string ofc
If you set ephemeral to true, yes

Like this custom check I made
You do await ctx.respond("msg", ephemeral = True)
;D
Yeah I agree
It's so simple to use
I am not switching back to dpy because Pycord is being updated and it's easier to use
I need to update my bot now to pycord
Since I discovered it i'm learning a lot of easier ways to improve
Now i'm stuck with another issue, what if someone calls the bot by prefix? it tells me ephemeral is not a valid keyword
Hello,Could someone give me an example to make a persistent button in a cog? Thank you
The pycord master branch has an example I think
I did not find
Is there a way to check in bridge if the bot has been called by prefix or slash command?
Yes, actually there is example right in docs
Did a workaround with try,catch
Detects a type error of the keyword and just responded to that
Can I use discord.option is a modal?
Another little question, is there a way to check if bot is connected to a channel?
Can someone please explain me how this works?
@bot.command(name="test")
async def test(ctx: commands.Context, channel: discord.TextChannel):
print(channel.name)
INSTEAD OF:
@bot.command(name="test")
async def test(ctx: commands.Context, channel_id: str):
channel = bot.fetch_channel(channel_id)
print(channel.name)
So it basically creates the TextChannel object just with the channel id or mention. How does that work? Is there a method that gets called or how does it know to create the TextChannel object? Can I also use this in my code like channel = discord.TextChannel(channel_id) or something like that?
no, short/long text input only (discord limitation)
I don’t think so, since TextChannel is calling for an argument in a command
there's code in command that calls fetch_channel for you. if you want to do it in your own code you will haev to call fetch_channel, or use discord.utils.get
Yes
ok thx
check if ctx is instance of BridgeExtContext or BridgeApplicationContext.
in nutshell ; it uses concept of annotations (https://peps.python.org/pep-3107/)
so library knows what you provide after colon and the library logic: since it is TextChannel class let s convert whatever the input it got into that arg with TextChannelConvertor class which basically fetches the channel like your second code but with checking all cases ;
Yeah I noticed that after and fixed my code but tnx for answering!
Pycord/discord.py is able to look at the type annotations that you give (using the inspect module)
Normal this would only be type hints and do nothing at the runtime lvl.
However since pycord checks at runtime what typehints you provided it is possible for the lib to call a converter that is able to convert the name/channel_id that is provided and retrieve a object of target type (your annotation) from the cache and pass it in as the method parameter instead of the true value the user provided.
This is not magic so it does not work with every object someone needs to write a converter for it you can also write a converter for your custom objects in pycord.
(To give a moire detailed answer)
great answer, thanks 🙂
It's more a general python question but is there any difference in performance between type(a) is b and isinstance(a, b)? Both ways should always give the same output right? I find the first option actually more readable, so there is the question of the "performance". I know, both of these ways of checking the type are probably nearly equivalent in speed but there has to be a ever so slight difference. So what do you think (or know) is the faster one?
pretty sure performance wise there is not much of a difference. however, checking type(a) is b doesn't account for inheritance things while isinstance(a, b) does
so isinstance checks if b is somewhere in a's inherites types?
https://stackoverflow.com/questions/1549801/what-are-the-differences-between-type-and-isinstance this one does a pretty good job at explaining the difference
thx
Is it possible to use Subcommand groups in cogs, and if so, how?
yes, https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_cog_groups.py
GitHub
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/slash_cog_groups.py at master · Pycord-Development/pycord
Thanks
I'm getting this error with this piece of code await context.respond(f"Playing: {video['title']}")
discord.commands.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
Could someone please tell me why I'm getting this error?
Code:
#search
def search(query):
with YoutubeDL({'format': 'bestaudio', 'noplaylist': 'True'}) as ydl:
try:
requests.get(query)
except:
info = ydl.extract_info(f"ytsearch:{query}", download=False)['entries'][0]
else:
info = ydl.extract_info(query, download=False)
return info
#command
...
@music.command(name="play",description="Plays a song")
async def play(self, context,*,query):
member_voice = context.author.voice
if member_voice and member_voice.channel:
if context.voice_client:
pass
else:
await member_voice.channel.connect()
if self.query != []:
video = search(query)
emb = discord.Embed(title=f"✅ Queued {video['title']}", color=0xff2700)
self.query.append(video)
await context.respond(embed=emb)
if self.query == []:
client_voice = context.voice_client
self.voice_client = context.voice_client
self.voice_context = context
await context.trigger_typing()
video = search(query)
source = video['formats'][0]['url']
emb = discord.Embed(title="Now playing", description=f"[{video['title']}]({video['webpage_url']})\n**Uploader:** {video['uploader']}", color=0xff2700)
emb.set_thumbnail(url=video['thumbnail'])
client_voice.play(FFmpegPCMAudio(source,**FFMPEG_OPTIONS,executable=exe))
self.np = video["title"]
self.query.append(video)
await context.send(embed=emb)
await context.respond("Playing requested song.")
await gettime(self)
await nextque(self)
...
The piece of code causing the error is video = search(query). Does anyone know why this is happening?
Hello, I just switched to the new update and I was wonderinf if theres a way to use is_owner as a decorator
@bot.slash_command(description="Kill the bot")
@bot.is_owner()
async def kill(self, ctx):
print("BYE!!! (Killed through command)")
quit()
Though bot.is_owner seems to be a check that required a user to check against and not a decorator, anyway I could use this as a decorator?
While you're finding this out you can just use an if statement to check the user ids
nvrm built in decorator through ext.commands mb
You just say what you need help with and someone will help if they know the answer
!ask
Er. Am I doing something wrong here?
Trying to use guild.get_channel() or even just trying to browse guild.channels results in the following
AttributeError: 'TextChannel' object has no attribute 'news'
Full traceback?
Traceback (most recent call last):
[pycharm/ipython stuff]
File "[python]/site-packages/discord/channel.py", line 190, in __repr__
attrs = [(val, getattr(self, val)) for val in self._repr_attrs]
File "[python]/site-packages/discord/channel.py", line 190, in <listcomp>
attrs = [(val, getattr(self, val)) for val in self._repr_attrs]
AttributeError: 'TextChannel' object has no attribute 'news'
using rc1
discord/channel.py line 711
return super()._repr_attrs + ("news",)```
that shouldn't be there
git blame
blame bob
I'm getting an odd error from my code, could someone please help me?
Code:
@music.command(name="play",description="Plays a song")
async def play(self, context,*,query):
member_voice = context.author.voice
if member_voice and member_voice.channel:
if context.voice_client:
pass
else:
await member_voice.channel.connect()
if self.query != []:
video = search(query)
emb = discord.Embed(title=f"✅ Queued {video['title']}", color=0xff2700)
self.query.append(video)
await context.respond(embed=emb)
if self.query == []:
client_voice = context.voice_client
self.voice_client = context.voice_client
self.voice_context = context
await context.trigger_typing()
video = search(query)
source = video['formats'][0]['url']
emb = discord.Embed(title="Now playing", description=f"[{video['title']}]({video['webpage_url']})\n**Uploader:** {video['uploader']}", color=0xff2700)
emb.set_thumbnail(url=video['thumbnail'])
client_voice.play(FFmpegPCMAudio(source,**FFMPEG_OPTIONS,executable=exe))
self.np = video["title"]
self.query.append(video)
await context.send(embed=emb)
await context.respond("Playing requested song.")
await gettime(self)
await nextque(self)
The piece of code that is giving me errors is video = search(query) the code for that is:
def search(query):
with YoutubeDL({'format': 'bestaudio', 'noplaylist': 'True'}) as ydl:
try:
requests.get(query)
except:
info = ydl.extract_info(f"ytsearch:{query}", download=False)['entries'][0]
else:
info = ydl.extract_info(query, download=False)
return info
The error:
not sure if i'm somehow missing something in the documentation, but is the message returned from wait_for when waiting for the message event NOT supposed to have content? it gives me effectively everything except the content. it's also not an issue of perms, because if i do a fetch with the ID it retrieves the content perfectly fine. small sample of code here:
msg: discord.Message = await bot.wait_for("message", check=check, timeout=5)
print("Content", msg.content)
other_ctx = ctx.channel.get_partial_message(msg.id)
print("Other content", (await other_ctx.fetch()).content)
For reference i'm not getting the standard msg.content on both whatever build i was previously on as well as rc1
message_content intent, if youre missing it then your bot is not getting message content
i have the message content intent, and i don't think it would let me retrieve the text by using fetch with the message id if i didn't either
¯_(ツ)_/¯
i'm pretty sure it's a bug but i'd like a second opinion if someone is willing to see if they have the same issue
How can I set the default member permissions for a slash command group?
I use windows and if i try to send audio packets, something happens like this (no idea what missingsentinel is):
File "C:\Users\hhh\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\voice_client.py", line 905, in send_audio_packet
encoded_data = self.encoder.encode(data, self.encoder.SAMPLES_PER_FRAME)
AttributeError: '_MissingSentinel' object has no attribute 'encode'
Im using the new Version of pycord and now the Bot dont create Slashcommands. The bot can create Slashcommands and has Admin Permissions
Both commands dont show up
If you don't specify commands to be guild specific they're global so take much longer to sync
i had a command before only for the guild but that didnt worked
Even with debug_guilds its not working. iirc It should take a maximum of one hour
how do I set slash commands to only work for the bot owner?
Somehow in a Cog it works instant. Without a Cog it doesnt work at all
because outside of a cog you have to use the decorator from the bot object
e.g. @bot.slash_command()
@shell tide
when i click on button it successfully executes the block of code in button_callback but for some reason im getting "This interaction failed" at the end. No errors though.
import discord
class WarPostView(discord.ui.View):
def __init__(self, bot : discord.Bot) -> None:
super().__init__(timeout=None)
self.bot = bot
@discord.ui.button(emoji="🔴", custom_id="stream", style=discord.ButtonStyle.gray)
async def stream(self, button : discord.Button, interaction : discord.Interaction) -> None:
user = interaction.user
message = interaction.message
emb : discord.Embed
for emb in message.embeds:
for i in emb.fields:
if(i.name != ":red_circle: Stream") : continue
if(i.value == "-") :
i.value = user.mention
break
if(user.mention in i.value):
i.value = i.value.replace(f"<@{user.id}>","")
if(i.value == ""):
i.value = "-"
else: i.value = f"{i.value}\n{user.mention}"
await message.edit(embed=emb,view=self)
because you never respond to the interaction properly
change the edit line to be await interaction.response.edit_message instead
i see let me try that
ty!
whoops accidently replied to u
#976366303176716339 ive been waiting for like a whole day noone responded, (this is a re post because I lost the old post and it got archived
How Do you make a so clean Screenshot? 😳
prob a sharex filter
Codesnap extension in vscode
Is there a new Method to check if a User has a certain Role for a Command?
@discord.has_role() is no longer available
its @commands.has_role()
how do i send norm text and embed in a single message
do await ctx.send("whatever", embed=yourembed)
provide both params
your welcome :D
Hey guys I got a question, are cooldowns working for you? Cause mine are not working on latest GitHub Version
Hey, I was wondering if there's a way to get the guild out of a VoiceProtocol? I can get the guild thats why i'm asking
No, I don't think so
