#Basic Pycord Help (Quick Questions Only)
1 messages · Page 14 of 1
im new to all this coding stuff
im tryna help my friend
so
i might aswell try to learn

how do you remove a role from a user when only having their id?
get the user object from id
user doesnt have remove _ roles though?
member = discord.Guild.get_member(ctx.guild, int(discord_id))
you need a guild object, and just pass id into .get_member()
you can get a guild object from... well... id, event, or context
Bot.fetch_member(id).remove_roles(role)
Oh is it get member
I thought buckettype.user meant each user gets their own bucket?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'group'
it might be a really dumb mistake by me but i know like nothing about python
why did it not format
?tag codeblock
Please put your code in a code block:
```py
Here is your Code
```
That makes reading code in Discord a lot easier:
print("This is an example.")
ohh
what is _?
i read that it takes the value of the last operation. i'm completely misusing it here am i
Oh, yeah I would recommend just storing in a var so that your code is easier to read and debug
this returns the same error
@bot.command()
async def translate(ctx: commands.Context, input: str = "texto de prueba. reemplazar con mensaje basado en contexto." , outlang = "en", inlang = "auto", result = "welp something's wrong"):
"""Translates."""
result = translator.translate(input, src=inlang, dest=outlang)
await ctx.send(f"{text} -> {result}")
wait the result doesn't go there i'm dumb
do i define it inside the body?
why doesn't it go there?
because the user would be able to pass the content of result as an argument
hi, exist the event to create channel ?
right, take off result from the arguments
in all of these using 'these' and "these" doesn't make a difference, does it?
nope
I removed my "on_timeout" function for each view and turns out removing that solved the problem of the images randomly disappearing from the api. kinda odd.
This is the function each view uses:
async def timeout():
try:
await msg.edit(view=None)
except:
pass
view.on_timeout = timeout
okay i figured it's something outside my code because the examples in the repo return the same errors
On the stable version Is there any way to make slash commands hidden for users who don't have a certain role?
You can manage that on the integrations tab on your server
OKAY I GOT IT WORKING somewhat. it was a known error with googletrans 3.0, it was fixed in the 4.0 release candidate. now it spews too much data which is good i suppose, just gotta filter out the bits the end user doesn't care about
>>> print(translator.translate('bolas de queso'))
Translated(src=es, dest=en, text=Cheese balls, pronunciation=None, extra_data="{'confiden...")
how could i print only the text?
how to extrac id the channels in event on_guild_channel_create
YES
Oh. Hi. I was also having that issue. 4.0 fixed it?
yeah, 3.1.0a0 works too
Thanks. How did you get the text? Just translated.text?
if you want to use 4.0 install it as googletrans==4.0.0-rc1
Does PyCord have anything for creating private messages? I don't mean a direct message in your inbox.
I mean a message in a normal server channel that only a specific user can see.
Sometimes I've seen Discord spit out messages labeled with "only you can see this message" and a dismiss message option.
Is it possible to do that?
i defined output as translator.translate(input) and printed output.text
Those are interactions as ephemeral=True. Interactions as in slash commands, buttons, context menus
Awesome. Thanks.
thank you
for interaction.response.send_message or ctx.respond, you want ephemeral=True
only available for slash commands and ui components
another question, if i wanted to send a command like for example .bot translate some text en es that translates from english to spanish, is it only possible if the text (everything before the language arguments) is in quotes?
Thank you both, Dark and Nelo!
allgood
not necessarily; if it's the final argument, you can separate it with * to capture everything
e.g. py async def translate(ctx, language, *, text):
would this work?
async def translate(ctx: commands.Context, input: str, * , outlang = "en", inlang = "auto")
no, you should have the input last
i see. quotes it is.
* can only be used for the last argument because otherwise it'd be too ambiguous
is it necessary for the languages to be last? it seems like better design for the user to have them before the text
i'm making it optional to specify the languages, letting the api autodetect the source and translate to english by default
also planning on making this work on replies
i think reading through Special Converters at https://docs.pycord.dev/en/master/ext/commands/commands.html#special-converters would help
is there a way to condense these down into maybe just the group in the /commands menu?
not now, but discord plans to rework how slash command groups are displayed
not sending any arguments and instead doing .bot translate. if it's replying to a message translate that. if not, translate the message right above.
tysm <3
by the way, is there a way to alias different keywords to a single command?
i reckon you'd be most interested in typing.Optional, though it'd need some more work
add aliases=[...] in the decorator
being a list of different names the command can be invoked with
the import im using inside models.py
@cyan quail why is that happening 
nvm
found why
@fiery tiger Don’t ping support members randomly.
How could I end a specific asyncio task with self.bot.loop.create_task
im trying to send a message to 1 specific channel in my server I have this
channel = client.get_channel(rcid)
await channel.send(embed=e)
but its not working for some reason
I got it to work
when I use an application context to access member.activities it returns none but works fine if it's a slash command. Both of them have the same code for the response part. Does anyone know why?
show code
line 4
import discord
from discord.ext import commands
pip freeze
emmmm
i fixed it
(delete discord file)
Is there a list of input types for options somewhere
I'm tryna get the one for like a person input type
passing most discord models will work, and ext.commands converters are supported
if you want the actual input types that you can send to the api take a look at the SlashCommandOptionType enum
where is that
should be in docs
Couldn't find documentation for discord.SlashCommandOptionType.
pass it as the first parameter to discord.Option
so for like mentioning a user you'd put "discord.user" at the start of an option?
Ok so I put it as the start and now whenever I do that command it just sends back "This command is outdated, please try again in a few minutes"
nvm I think that was something else
can i use bridge_command() in a slash sub command?
No we don’t support that
I don’t think so
Under what circumstances will a slash command id change?
Ignoring exception in on_message
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "/home/discord_bot/cogs/AutoEmoji.py", line 27, in on_message
await message.add_reaction("")
File "/usr/local/lib/python3.8/dist-packages/discord/message.py", line 1476, in add_reaction
await self._state.http.add_reaction(self.channel.id, self.id, emoji)
File "/usr/local/lib/python3.8/dist-packages/discord/http.py", line 356, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
Why do I have this error for the third day already? Everything was fine before that. Maybe I should put a delay?
from discord.ext import commands
import discord
class AutoEmoji(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_message(self, message):
if message.channel.id == 1005138960487559308:
await message.add_reaction("")
if message.channel.id == 1005138960487559308:
await message.add_reaction("")
if message.channel.id == 1005138960487559308:
await message.add_reaction("")
if message.channel.id == 1005084265156989039:
await message.add_reaction("")
if message.channel.id == 1005084265156989039:
await message.add_reaction("")
if message.channel.id == 1005084265156989039:
await message.add_reaction("")
if message.channel.id == 514580675479863296:
await message.add_reaction("")
if message.channel.id == 514580675479863296:
await message.add_reaction("")
def setup(bot):
bot.add_cog(AutoEmoji(bot))
code
If the changes are too major. Like name changes
Don’t post your question multiple times. You already asked that in another thread
One message removed from a suspended account.
One message removed from a suspended account.
getting the other guild with bot.get_guild method
Yes you didn’t get an answer. Wait for it.
Stop arguing with me and stick to the #help-rules. Otherwise you’ll leave this server faster as you expect
message was probably deleted before the bot could add the reaction
understood. thanks
One message removed from a suspended account.
send code
any idea how I would be able to check if the bots missing permission with out using try and except
One message removed from a suspended account.
what is guild_public?
One message removed from a suspended account.
what is the guild= parameter?
One message removed from a suspended account.
so like if we want to mention slash commands in help commands,
we first need to push the changes in main bot,
wait for commands to appear
then copy id and design help command again
push changes again?
One message removed from a suspended account.
- fetch the guild ✅
- check to see if the name is in the roles ✅
- get the user inside of the guild ⚠️ (check to see if their in it and to use the member class)
- use the member.edit method from step 3 variable ⚠️
the steps should work
One message removed from a suspended account.
One message removed from a suspended account.
member = guild_public.get_member(after.id) most likely
One message removed from a suspended account.
are you trying to edit the user in that specific guild or the current guild?
hmm idk, pycord handles it weird
@lilac turret do you know more
One message removed from a suspended account.
ight
try using the code now
One message removed from a suspended account.
hmm
after the commands are registered bot.application_commands will have a list of them, and the id attribute will be up to date
would add a little check to wait until they're finished syncing to make sure the help command doesn't run before
otherwise it's mostly the same
I'm still getting the 50027 error from editing interaction messages, but I think I saw that was fixed? Or am I mistaken
10 hours ago, which version do you use?
not a version from within 10 hours ago lol mb
use the dev version
remind me how i do that
#library-updates first message in there
is there mention attribute straight?
nvm i make it if not
</name:id>
when I use an application context to access member.activities it returns none but works fine if it's a slash command. Both of them have the same code for the response part. Does anyone know why?
why isnt there a stickers arguement in the send_message interaction response?
whereas in send there is
sum1 forgor
How do i stop bot from turning links inside a message.content into an embed below the message ?
From what i can tell, difference is message flag being 100 and not 000 but setting it to that value on every message just sounds like a recipe for a bad time later down the line
hello does anyone knows how to but a bio to the bot?
set the application description in the dev portal
you can surround links with <> and they won't embed
https://nextcord.gay won't embed
https://nextcord.gay will embed
i need to specifically not use this approach for a number of internal reasons.
well your other alternative is suppressing embeds with message flags
looking through source code, i might be able to manipulate via
yeah, that's what i thought. thanks anyway
it's my first time trying it so i'm sorry if i made a silly mistake
can somebody tell me what's wrong in the terminal?
I already installed the latest version of python 5 minutes ago
can you run just python
and then try to install pycord?
well see if python works as opposed to python3
it's opening microsoft store for some reason
did you add python to path
yes
anyone can help page system, i cant understand doc
there would have been a little checkbox in the installer
yes
i pressed on both
restart your terminal and try again
it works on my windows machine
bruh i was reading the guide
(we're not allowed near hard commands)
so does anybody know what i should do now?
realistically i'd advise creating a venv
or you can directly install the packages like in the guide and make a main file for the bot
Hello @round rivet do you know how pages works ?
No
does the installation make any files?
or do i have to make main.py or something myself
installation installs the library and that's it
actually it also creates venv
everything else is done yourself
bruh
apparently you can't directly set flags when sending the message via messangeable.send 💀
still looking for any advice on how to send messages without embeds but without replacing links with <link>
you should be able to
ig it's not supported in the library
if you want you can make a pr to add support for it :p
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
actually the documentation states that you can only set the supress embeds
so the only thing i need
i'll try to figure out how to properly add something like supress_embeds, but the implementation is bound to be horrible
sorry to ask something that's probably been answered but i can't for the life of me find it. how do you get the id of the message that called the bot?
yes
what's the context
i'm pretty sure guide is a bit outdated last time i tried it
but can't say for sure. drop your codem pls
if you use prefixed/slash command, use ctx.message.id, if you use context menu you should have ctx and message if your function and message.id should work
i'm using prefixed commands with @bot.command
ctx.message.id, I'm not sure ctx.id is a thing on prefixed commands
didn't work
^, had context menu in my mind when answering that
i just installed dotenv pycord right now
i thought the problem is from that but my bot is still not online
looks like you're missing the bot.run
should be at the bottom of your file if you reference the guide
i use notepad++ only because i like working at night and notepad blinds me lmao
i'll write and indent the code myself thank you
Why not vscode and darkmode?
too slow and complicated for monkey brain
It is not slow
it also doesn't recognize the installed packages for some reason
it takes a bit to start while a plain text editor takes like nothing
i just don't see the need to use vs and vsc if what i have works well enough
message send supports it too it just isn't in the library for some reason
i tried disnake too, i have errors there too
seems like python isn't my thing
thanks for the help
I can't seem to be able to edit attachments in a message - an image, to be exact, can't remove existing files.
Is this a problem on the part of my code or a result of File objects being single-use and discord being naughty ?
code in question
I would add a check to that wait_for
check if it contains attachments and get attachment list from that ?
well firstly check who sent the message and where
otherwise ittl take in any message from anywhere
oh, fair
An example, initially message had 2 attachments, i'm replacing it with content of my reply answ, its content and its files via list()
but the message still keeps both the images
This all works if the initial message had no images
So either there's something seriously wrong with my code
or it's discord limitations
and the only one who can reasonably answer it is somebody that understands the discord API and its limitations better than i do
how to change the button label in calllback?
button.label = "something"
not working
then just edit the view
hm
?tag idw
Saying it doesn't work or asking what's wrong with this code? is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.
how can i use formatted strings in decorators?
okay, it's a case of me being a dunce but discord being naughty
just in case you wanted to know the reason
any idea how to fix this in vsc?
trying to install pycord using terminal in vsc, this error keeps appearing.
Maybe install python on your machine.
this should return true if the command was sent while replying to a message, right?
if ctx.message.reference is not None:
What does invisible do in deferred responses? the docs don't seem very clear
messages only reference something if they're replies, crosspost by a followed channel, or pins, but only replies can send a message at the same time, so in theory it should run only on user messages
Does anybody know if it's possible to send a modal using a followup webhook (or similar) instead of using the interaction.response object? Either because it's already been responded to or because of the 3 second timeout
Unless you attach a button in the follow up response
Unfortunately not. InteractionResponse or interaction.response has its own send_modal function. Therefore, you can’t use interaction.followup. […]
Yeah I figured ... sad. Thanks
sends a deferred update message on button interactions if set to true
therefore making the response 'invisible'
because it appears to just stop the loading animation
its alreday installed.
this is in my appdata
are ctx.message.id and ctx.reference.message_id both correct?
ctx.reference is the replied-to message
and in my example it gets the id of the message the user replied to, right?
ah okay, thanks
i still cant install pycord on my com smh-
this is happening when im trying to install pycord
use the regular command line outside of python
just open cmd and type pip install -U py-cord --pre
still doesnt work
anyone know if channel.history(limit=3) would return 2 or 3 messages?
i'm talking if limit is the maximum or the ceiling
Use discord.Bot instead of discord.Client
bot should be capitalized
I have a quick question. How do I disable slash commands?
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\discord\client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "c:\Users\����\Desktop\���� ��� �����\Caramel\cogs\AutoEmoji.py", line 31, in on_message
except discord.errors.NotFound(response, message) as e:
NameError: name 'response' is not defined
What's wrong with him?
@commands.Cog.listener()
async def on_message(self, message):
await asyncio.sleep(5)
try:
if message.channel.id == 1002208210809266247:
await message.add_reaction("🔱")
if message.channel.id == 1002208210809266247:
await message.add_reaction("😢")
except discord.errors.NotFound(response, message) as e:
print(e)
@commands.Cog.listener()
async def on_message(self, message):
await asyncio.sleep(5)
try:
if message.channel.id == 1002208210809266247:
await message.add_reaction("🔱")
await message.add_reaction("😢")
except discord.errors.NotFound as e:
print(e)
I removed the if statement since it was the same ID, no need to check twice
no spoonfeed
The problem was that you dont need to call it as a function
Just the type of error raised
in a channel, for a user, or make a bot not use slash commands?
anywhere. I am implementing a maintenance function, and while this is enabled I do not want anyone to be able to execute any commands
U could set the command to only load on your private guild, and that way u have access to the cmd, while others dont
you can disable slash commands for @еveryone but if other roles have the permission you'll have to do the same for those
Okay thanks!
actually yeah disabling slash commands from a bot to all servers but one seems like the better option, doesn't stop users from using other bots' slash commands
from discord.ext import commands
from Utils import embeds
class Clear(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
@commands.has_permissions(administrator=True)
@commands.guild_only()
async def clear(self, ctx, amount = 0):
if amount <= 0:
await ctx.reply(embed=embeds.default_description("Invalid amount of messages, senpai~"))
return
await ctx.channel.purge(limit=amount)
await ctx.reply(embed=embeds.default_description(f"{amount} messages were deleted with success!"))
@clear.error()
async def clear_error(error, ctx):
await ctx.reply(content=error, embed=embeds.default_description("An error has been found, sorry senpai..."))
def setup(bot):
bot.add_cog(Clear(bot))
It says the clear command doesn't exist even tho it is being loaded
what's the best approach to making consistent has_persmission checks but also excluding the owner from them ?
since checks are AND operator and not OR, i would need to rewrite has_permissions in the module to include part from is_owner, right ?
Are you sure it's being loaded?
yea
Loaded cog Commands.Admin.clear
Loaded cog Commands.Testing.teste
Extensions store errors if they raise some
is the triple quoted description next to a command's decorator required for it to work or can i remove it?
Add store=False to your load_extension function
Which triple quoted description?
@bot.command()
async def translate(ctx: commands.Context, input = ".", outlang = "en", inlang = "auto"):
"""Translate"""
the Translate part
Ah
That's used for functions descriptions. You don't need it, won't affect the command
Is create_group class possible in cogs? 💀
Here's the slash cog groups example.
ok ty @prisma flicker
does on_message trigger before adding a message to cached_messages?
also how many messages will the bot cache?
using the on_member_join(member) can I do on_member_join(member, guild) to get server information
i wasn't actually sure on this, but surprisingly yes py message = Message(channel=channel, data=data, state=self) # type: ignore self.dispatch("message", message) # on_message if self._messages is not None: self._messages.append(message) # _messages is client.cached_messages
by default the message cache is capped at 1000, but you can modify this by setting the max_messages kwarg when creating your bot object
ok
How can I make the bot get all the IDs of the servers he's in it
when should i use get_message or fetch_message?
Use a for loop. Here's an example:
guild_ids = [guild.id for guild in self.bot.guilds]
I believe that get_message is used if the message is already cached, but fetch_message makes an api request to get the message details
is the pycord guide on the site outdated?
What would i use to make something like this, if i use title and url how would i make it bold lettering
you can use get_message, see if it's None, and then fetch
assuming you know the message (should) exist
if you're not sure I would just use fetch
.
i'm so confused on why my commands aren't working
https://mystb.in/ExerciseRebelAcademics
One message removed from a suspended account.
you're checking not after.channel so it will always be None
..
How make an option in Slash command optional
One message removed from a suspended account.
Can someone help me ive been waiting a while
@prisma flicker possibly
[link](paste link here)
Yes
please don't ping me
What would i use
It will work in an embed
try it and see
My bad
#help-rules
No idea what your talking about
I am trying to figure out what parts of the embed do i use
Let's say u want to make go here as a link
No
Ok?
Like i want to make something like that embed
A clickable word
Not a link embed
I know what a hyperlink is
One message removed from a suspended account.
How make an option in Slash command optional
I want to know how to make my embed look like that because its ovb not a title and desc
Wdym
Thats a confusing question
set required=False and give it a default value

What parts of the embed do i use to make my embed look like this
description? you can put whatever text you want there, in whatever format
Im confused
I cant leave a title empty tho
That is ovb not a desc its too bold
By bold i mean more color
hey does anyone know how like when you click a button a modal will pop up?
Eh dont worry about it
instead of having to do a diff command
The hyperlink is my biggest issue, how do i do that, how to make it bold
bruh wdym don't worry about it
Im not making sense
hey does anyone know how like when you click a button a modal will pop up?
How to i make the hyperlink with a description
@hearty mauve like this ^
yo @ jb
@prisma flicker
dyk know how like when you click a button a modal will pop up?
s!jsk py py embed = discord.Embed() embed.description="**[Hello](https://google.com)**\n\nHere is some normal text" await _ctx.send(embed=embed)
why not
and the examples and the guide
will that do this?
there's an example of how to do that yes
K that's sick
it's just jishaku
when i do it everything below it turns orange
like all fo the code below where i put that in
I have no idea what you're saying
im so confused rn
@prisma flicker is this your bot?
<@id> isn’t pinging me
yes
When I have my bot send it
Is it made in dpy?
yes
Oh alright for a sec I was thinking that Jishaku had made it so you didn't to use dpy
s!jsk py py await _ctx.send(discord.__version__)
2.0.1
oh no it's pycord
Huh
Please put your code in a code block:
```py
Here is your Code
```
That makes reading code in Discord a lot easier:
print("This is an example.")
whats that
I use version jishaku==2.3.2 which works with pycord
but I heard newer versions work with pycord now
Ok thanks
can u look at it and tell me where i would put this in
can you at least set the file as python so it gets syntax highlighting
rename it to file.py
why do you have two bots
i dont
line 8 and 10
you just need to call send_modal in the button callback where you want the modal
it's covered in the docs
The master version has dpy in the reqs
yeah so does 2.3.2
but it still works 
I think 2.3.2 requires 1.7 though
I don't remember, I just know this works 😄
I can't find it in the reqs
link it to me 😂
Here's the modal dialogs example.
i have all that
then you have a modal from a button
Sorry i have a question that's a bit out of pycord help support or in general bot supports
what's this tax form review about?
im using W-8IMY because that's why recommended from the questionnaire
do i just use W8IMY pdf file?
that's the only thing they make me download
it tells discord how much tax to withhold
I have no idea if W-8IMY is the right form, I'm not a lawyer or accountant
😂
input = await ctx.channel.fetch_message(message.id)
await ctx.send(input.content)
how could i change this such that input alone contains what would be sent?
input = await ctx.channel.fetch_message(message_id).content
i have a slash command that people are only meant to be able to do once, and it works, but when discord lags and you spam the command it lets u do it like 50 times and idk how to get aroundt hat
what cooldown are you using
if it's a dict then that would filter immediately no? how did you implement it
and im pretty sure you can't even spam it that fast
its just if ctx.author.id in dict: return do whatever
obv indented
it never happened before but someone spammed it and managed to do it like 6 times
i feel there's something missing here... if it's a simple dict then you wouldn't be running into a race condition like that
i thought it might be because the command is being ran a 2nd time before it can add them to the dict and not let them do it again
like
users = {}
@slash_command(...)
async def command(ctx):
if users.get(ctx.author.id): return await ctx.respond(...)
users[ctx.author.id] = ...```there's clearly no room here for it to be abused, unless you're somehow using different dicts every time the command runs
like... loading it from a json
i do load it from a json but not when command is ran
gimme a sec
its a bit messy bc i made it ages ago but
i cant even send it
hold on where can i upload it
use hastebin or something i guess
theres other stuff
but it should have been deleted from marketData to not let them do it again
but they managed to spam it
well your issue is that you delete from marketdata at the end of the command
why don't you just add a cooldown to it
allgood
your case would work much better with a cooldown
yea
i think it was bc of that bug on mobile where sometimes when you spam send it sends it like 10 times
so it let them do it like 10 other times before it stopped them
does it have to be run once per user, once per guild or
i was just simplifying it bc it was too long to explain once you buy a card you cant buy it again bllah blah blah
so per user
well per card
so once a user buys a card the rest of the users can't
yea
but i gave it to them and then stopped them from buying it
so i guess if it was ran at the same time it would give it the 2nd time before deleting it the 1st time
Can I use slash commands and normal at the same time?
you can do it with a bridge bot
Concept
Here's the bridge commands example.
ty
o/
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'is_app'
?
any idea how to fix this?
Does it make a difference to run an async database on a different loop as the bot?
?tag client
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
this is happening though
are you using discord.py or pycord?
pycord.
could you check
alr lemme try
do pip freeze
it gives stufff like this
can you show the pip list?
look for py-cord
do pip show py-cord
and discord?
can you show the pip list?
Read this to find out how you can install Pycord in replit - https://namantech.me/pycord/installation/#replit
This might help
Use commands.Bot
Scroll up, someone told them to do that already
Where might I find guidance on slash commands in cogs?
did they? I don't see anyone specifically saying that
Here's the slash cog example.
@short coyote
they just used the client tag
Thank ya sir
I’ve been able to get slash commands working in the main.py file but not yet in cogs so I appreciate the assistance
Traceback (most recent call last):
File "main.py", line 7, in <module>
bot = discord.Bot(debug_guilds=[1012074059976155137])
AttributeError: module 'discord' has no attribute 'Bot
how to fix
you update py-cord
?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
@bot.event
async def on_message(message):
if message.channel.id == SOURCE_CHANNEL:
if USE_WEBHOOK:
requests.post(WEBHOOK_URL, json={"content": message.content})
what is wrong here? nothing gets sent
do you have message content intent?
can you print(message.channel.id, SOURCE_CHANNEL, message.channel.id == SOURCE_CHANNEL, USE_WEBHOOK)
at the top
anyone know what this means?
fsdfsdfds dfssfddfs True True
replaced channel and source
but they are the same
the error tells you what's wrong
?tag lp
Official Beginner's Guide: https://wiki.python.org/moin/BeginnersGuide
Official Tutorial: https://docs.python.org/3/tutorial/
Shortcuts:
https://wiki.python.org/moin/BeginnersGuide/NonProgrammers
https://wiki.python.org/moin/BeginnersGuide/Programmers
Learn Python:
https://automatetheboringstuff.com/ (for complete beginners to programming)
https://learnxinyminutes.com/docs/python3/ (for people who know programming already)
https://docs.python.org/3/tutorial/ (official tutorial)
http://python.swaroopch.com/ (useful book)
http://www.codeabbey.com/ (exercises for beginners)
so the post isn't working
try running the post by itself, like just in a python shell
@bot.event
async def on_message(message):
if message.channel.id == SOURCE_CHANNEL:
if USE_WEBHOOK:
async with aiohttp.ClientSession() as session:
async with session.post(WEBHOOK_URL, json={"content": message.content}) as resp:
print(resp.status)
is this wrong? gives a 401 status code
yes
this link doesnt work
thanks that worked
didnt know it supported that
sweet
how do you do that?
it says name commands is not defined
you need to import it
i already imported discord/
from discord.ext import commands
oh it needs a command prefix how'd u do that
so give it a command prefix
but isnt it supposed to be slash commands
it's both
oh.
thats nice its similar to discord.py
whats this error-
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix = "?", intents=intents)
@bot.event
async def on_ready():
print(f"We have logged in as {bot.user}")
bot.run("my token(yes i did change it)")
this is my code
well its fine i can just reset it
has something like this
you're being rate limited
Yep
If that is cloudflare ratelimit then its a ip rate limit, they usually last a bit (few hours I think)
You should consider changing hosts
Shared hosts like that are always going to have rate limits
?tag norepl
Why NOT to use Repl as a hosting platform
You should not use Repl.it to host your bot.
It may be a nice option as its "free" but you should use something else considering the major flaws.
- The machines are super underpowered.
-
- This means your bot will lag a lot as it gets bigger.
- You'll need a web server alongside your bot to prevent it from being shut off.
-
- This isn't a trivial task, and eats more of the machines power.
- Repl.it uses an ephemeral file system.
-
- This means any file you saved via your bot will be overwritten when you next launch.
IMPORTATNT
- They use a shared IP for everything running on the service.
This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.
Please avoid using repl.it to host your bot. It's not worth the trouble.
If you're looking for free options, consider using AWS/Google Cloud Platform/Azure and its respective free tiers or just pay for an actual VPS.
is there a way to make a bot say something in the channel it joined in when it joins
There's on_guild_join
I know but im trying to say a message like "Thanks for adding me" when the bot joins im not sure how to do that
You would be just have to get a channel from the guild and then send a message to it
@bot.event
async def on_message(message):
if message.channel.id == SOURCE_CHANNEL:
if USE_WEBHOOK:
if message.embeds != []:
await bot.send_webhook(WEBHOOK_URL, content=message.content, embeds=message.embeds, avatar_url=message.author.avatar_url, username=message.author.name)
is this code correct?
the sending embeds part
I don't think it'll work if embeds or content are None
Or maybe only if both are None?
any idea why bot object has no attribute 'slash_command' happens?
im using bot = command.Bot
Exactly
@tidal prawn are you positive that you don't have discord.py installed?
That's not the same thing as telling them to use commands.Bot
Here's the new member example.
How many inputtext fields may a modal have?
im pretty sure.
and my python isnt working on vsc for some reason
Here's the slash options example.
Hey how can I get a channel with a mention like #channel?
But where can I find it. Can you send me the link?
Does it make a difference to run an async database on a different loop as the bot?
are there a list of overrides for issuing perms for creating text channels? I'm trying to find it, but 0 luck in finding them
elaborate? not sure what you mean here
for the overwrites parameters, are there a list of stuff that I can find so ik what exactly to pass in into the overwrites
overwrites is a dict that should map an Object such as Role or User to a PermissionOverwrite object
Do I need the guild indent to check if a user has a specific permission?
Hmmm, I'm still confused on that, there's not much explanation of list on the perms that you can overwrite
it literally says
The values supported by this are the same as
Permissionswith the added possibility of it being set to None.
anyone?
probably members intent too
for ctx.author.guild_permissions.administrator ?
cause this, without any indents gives None
@bot.slash_command(name="blacklist", description="blacklist a user")
async def blacklist(ctx, *, user: Option(discord.User, "blacklist any user", required=True)):
await ctx.defer()
await conn.fetch('CREATE TABLE IF NOT EXISTS blacklist_mfs(userid BIGINT NOT NULL PRIMARY KEY, username VARCHAR(50) NOT NULL)')
check = await conn.fetch(f'SELECT EXISTS(SELECT 1 FROM blacklist_mfs WHERE userid = {user.id})')
if check == True:
await ctx.respond('User is already blacklisted!')
else:
await conn.fetch(f"INSERT INTO blacklist_mfs(userid, username) VALUES('{user.id}', '{user.name}')")
await ctx.respond(f'Successfully blacklisted {user}!')
hey guys i made a command, but the check doesnt work
what is the problem?
i cant find any solutions for it anywhere on the net
well
what does the first conn.fetch actually return
and is the second conn.fetch actually applying to the db
I don't think that's the issue
reading the discord docs for guild members, it doesnt mention anything about user permissions
the problem with it is how cache works
without the intents, members aren't cached so they don't have their permissions set properly
you'd have to fetch the member separately
try member: discord.Member = ctx.author
default it to None and implement extra logic inside the command
The following code is a really basic example of the issue I'm having.
Is it intended that the first respond (send_message) does not mention the user, while every respond after that (followup) does? I tried setting allowed_mentions but that doesn't help either.
If I remove the defer it does mention, however that ends up breaking the command because it ends up taking longer to process. ```py
@slash_command(name='test', description='...')
async def _test(self, ctx: discord.ApplicationContext):
await ctx.defer()
await ctx.respond(ctx.author.mention) # doesn't mention
await ctx.respond(ctx.author.mention) # does mention
for i in self.client.guilds:
guild = self.client.get_guild(i.id)
embed.add_field(name=guild.name, value=i.id, inline=False)
guild name is still none. I have no indents (i dont think I need them)
Yeah? Cause the docs doesn't mention that. nvm then
Update: You don't need it
you could use cogs and add the cog to the bot, or import the command and use add_application_command
ye i used add_application_command
Hello
Does anyone know how to show a slash command for specific roles/users
?
integrations menu
if you don't have the guilds intent, it doesn't cache the guilds at all so get_guild would be useless
could you show me an example please?
wait what- why?
it now requires a bearer token by discord, meaning authorisation with your user account; it can't be done with just a bot token
I don't mind doing that. How can I?
as in, you literally can't do it with a bot
I mean, it says "not synced" so there should be a way to sync with the bot
discord.js has it pretty sure
the way to sync it is to literally click there and hit sync
i didnt mean that
dont mind it
could you tell how to do it (set default hiding setting)
like preset it to show for only admins, or only a specific userid
well that's the discord.default_permissions decorator, but note this will only apply to newly registered commands https://docs.pycord.dev/en/master/api.html#discord.commands.default_permissions
ah, how do you un-register and re-register the commands
and you can't do it per role or user; this relies on them having a specific discord.Permission
remove the decorator > restart > add it back > restart
ah, is there a way to show it on only a specific guild? Does (img) work to do that?
guilds_ids is a list of guild ids (integers) to register the command to
yep so some commands show up in only a specific server, perfect!
Can't seem to register an extension discord.errors.ExtensionFailed: Extension 'testing' raised an error: AttributeError: 'Bot' object has no attribute 'add_command'
were the docs not updated ?
or am i not allowed to load the extension before the bot runs ? current setup looks like this
try:
...
except pycord.RateLimited:
...
```Would this work?
that example is for using discord.ext.commands.Bot, not discord.Bot
Hey I want to make a command where you need to give a channel id.
But I dont want to force the user to enable the developer settings.
I cant find it in the docs. How can I get the channel from this #channel
.
where you need to give a channel id
doesn't that imply you have to have developer settings enabled?
anyway if it's a slash command just use the discord.TextChannel option type
we don't have an exception for ratelimits

you'd have to check the text of it to see
does setup() also take that type of Bot object ?
as an argument
yes
idk check their docs but i don't think so
because it isn't really an error, the library warns you and automatically handles ratelimits
i wanna be-able to halt process's if there's a warning
i guess you could check bot.is_ws_ratelimited
good for them i guess
and what is it for prefixed commands?
I just dont wanna be bothered to check error messages
Its also forcing me to use bad practices 
it should be the same
ok thx
it isn't really that much more effort... but if you want it implemented idk suggest it with the /suggest command or make a feature request on github
and no one's forcing you to run into ratelimits

I dident say the ratelimit was forcing me to use bad practice i said the way i have to check for ratelimits is causing / forcing bad practices by not having a built-in method
make your own method then
What's wrong here? (in a cog)
async def verify(self, context: Context):
guild = self.get_guild(context.guild_id)
await self.User_Ticket_Channel.set_permissions(interaction.user,overwrites=discord.PermissionOverwrite(send_messages=True))
After a user clicks the claim button, I'm trying to change the channel's permission to allow the user to send messages but it's coming as invalid permission
i'd recommend not using the overwrites kwarg and instead just passing in the perms directly
example from docs py await message.channel.set_permissions(message.author, read_messages=True, send_messages=False)
Do i get it right: if i want to use extensions and cogs, i need to use ext.commands.bot instead of discord.bot, and the former doesn't implicitly convert @bot.command on a function to a slash command ?
So i need to replace every instance of @bot.command to @bot.slash_commands ?
on_guild_join
thanks
Yes
you can use cogs without ext.commands actually
but you need ext.commands.Bot for prefix commands
yeah, but i don't like how it looks in the code
If you're in a cog it would be commands.slash_command
@command is so much better than @safe inlet_command
it has to be explicit
i was trying to implement cogs as a way to separate functions into several files, but that means i need to pass in ext.commands.bot instead of the one i was using before
There's also bridge
?
no, as i said cogs work without ext.commands.Bot
so i'd need to use the same syntax
You already have a thread
and how would i achieve that ?
wdym
And I havn't gotten an answer
Yeah because you're not using pycord
Either way don't cross post
#help-rules
oh yeah, sorry, i was working on extensions and cogs at the same time and one error seems to have caused me to assume the add_cog also failed, thanks
how to use wait_for in dm?
i'm looking for how to use it in dms
How is using it in dms different than any other use case?
I'm using wait_for but it doesn't work in dm
can you show the code? it works fine in dms
async def create(ctx):
member = ctx.user
dmChannel = await member.create_dm()
await dmChannel.send("يرجى كتابة اسمك أو اسما مستعارا")
name = await client.wait_for("message", check = lambda message: message.author == ctx.author)
try comparing message.author.id and ctx.author.id
also you don't need create_dm, you can directly do member.send
can u send me ur code to try it
def setup(client):
client.add_cog(Commands(client))
didn't work
How can i save {} variables in json file?
I make it, but i've got this:
how can i make unclickable option after select? 

🤨
but it also turns off the menu completely
🤨

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: InvalidSchema: No connection adapters were found for
what's this?
what's the event when user join's tthe guild
on_guild_join
hey so my modal call back isnt being called heres my code
class MyModal(discord.ui.Modal):
def __init__(self, *args, **kwargs) -> None:
print('ran')
super().__init__(
discord.ui.InputText(
label="Minecraft username",
placeholder="",
),
*args,
**kwargs,
)
async def modal_callback(self, interaction: discord.Interaction):
print("Modal callback:")
await interaction.response.send_message(content='hi')
``` the ran gets printed but not modal callback
when i push submit
it gets sent when buton pushedpy @discord.ui.button(label="Join event", style=discord.ButtonStyle.green, disabled=False) async def confirm_callback(self, button: discord.ui.Button, interaction: discord.Interaction): self.database.insert_one(document={'user': interaction.user.id, 'linked': False}) print(f'button clicked by: {interaction.user}') modal=MyModal(title="Link to Minecraft") await interaction.response.send_modal(modal)
Rename it to callback instead of modal_callback
Here's the new member example.
oh it matters? i figuredit just picked first func
No, it has to be named callback
does buttons have to be named confirm_callback
If you're subclassing the button, then it has to be named callback but otherwise, like what you're doing here, you can name it whatever since your using a decorator
What's this warning about?
@bot.event
async def on_member_join(member: discord.Member, guild_ids=[767773860481073222]):
print("test")
guild = member.guild
member = discord.Member
#
role = discord.utils.get(member.guild.roles, id='767773860543987744')
await member.add_roles(role)
channel = discord.utils.get(member.guild.text_channels, id='1012417901812269186')
emb = discord.Embed(title=" ",
description=f":7_: {member}")
await channel.send(embed=emb)```
why it doesn't work
it does not event print "test" to console
One message removed from a suspended account.
because it only takes the member attribute.....
??
How can i fix this
learn python
Im learning
why do you do member = discord.Member???
so
@tasks.loop(seconds=24000)
async def autoannounces():
await bot.get_channel(914895886788735056).send("announce 1")
await asyncio.sleep(12000)
bot.get_channel(914895886788735056).send("announce 2")
does modals have a decorator
my friend told me to add this
then your friend dumb
yea
dude remove member: discord.Member
No
One message removed from a suspended account.
np
@coral kindle learn python before doing pycord thanks

change the edit message to a regular message edit (interaction.edit_original_message) and then use interaction.response.send_modal
probably
idk might work in theory
hmmm
what about self.view.message.edit
hmmmmmmmmmmmmmmmmmmmmmmmmmmm idk
knew it
it probably could but i'd need more context
you basically just need some way to get the original message object to your callback
because you can still do a regular message edit before responding
can you show more of the code
just the current class then i suppose?
...if possible
if anything, i could try work with just how the original message/view is sent
too many items in your view
need to use ActionRows for more than 5
yeah
though tbh at that point i'd prefer to use a dropdown
looks neater to me but personal preference i guess

you can try it, but if im not mistaken this only adds it for respond, not edit_message
nono
try await self.view.message.edit again
but there's a chance it still won't work
this that we tried before
did you update?
edit is a method
you need to pass in content
well yeah that's what Nelo was saying
message is None
yes
you can set self.message manually
self.message = interaction.original_message() or whatever
Traceback (most recent call last):
File "main.py", line 99, in <module>
bot.run(TOKEN)
File "/home/runner/koolaidman-1/venv/lib/python3.8/site-packages/discord/client.py", line 715, in run
return future.result()
File "/home/runner/koolaidman-1/venv/lib/python3.8/site-packages/discord/client.py", line 694, in runner
await self.start(*args, **kwargs)
File "/home/runner/koolaidman-1/venv/lib/python3.8/site-packages/discord/client.py", line 657, in start
await self.login(token)
File "/home/runner/koolaidman-1/venv/lib/python3.8/site-packages/discord/client.py", line 510, in login
raise TypeError(f"token must be of type str, not {token.class.name}")
TypeError: token must be of type str, not NoneType
how to fix
persistent views are not working for me. even when I pass a message_id argument to add_view()
View Class
class GiveawayView(discord.ui.View):
def __init__(self, id):
super().__init__(timeout=None)
button = discord.ui.Button(label="Enter", style=discord.ButtonStyle.blurple, custom_id=f"persistent_view:{id}")
async def callback(interaction: discord.Interaction):
modal = GiveawayModal(id)
await interaction.response.send_modal(modal)
# modal.childre
button.callback = callback
self.add_item(button)
Adding view on bot start:
@commands.Cog.listener()
async def on_ready(self):
giveaways = json.load(open("bot_config/giveaways.json", "r"))
for msg_id in giveaways:
view = GiveawayView(int(msg_id))
self.bot.add_view(view, int(msg_id))
add_view just takes in the view
TOKEN is None, so actually provide a value for it
i do have one
Send code then
hold on wait
i have somthing else i need help w
so i have another bot with a /ban command i created and i want the message to pop up in a embed thing not just like a regualr messgae
like the results of the ban
so how do i put it in embed
More features to make your bot cool and snazzy.
Yea but like it confuses me where I put the code in so where the results are embed
Like do I put a strip of code or sum idk
You can use an online embed builder if your confused on what attrs change what on the embed
new feature??
why does this not work sometimes in other servers

Can someone give me an example on using @before_invoke and @after_invoke to open a sqlalchemy connection?
What I have so far
db.py
async def db_engine():
engine = create_async_engine(
f'{dbcfg.proto}://{dbcfg.user}:{dbcfg.password}@{dbcfg.host}/{dbcfg.database}?charset=utf8mb4')
return engine
original = await interaction.original_message()
embed = original.embeds[0].copy()
embed.set_field_at(1, name='Current bidder',
value=f"{interaction.user.mention} ({interaction.user.name}#{interaction.user.discriminator})",
inline=True)
embed.set_field_at(2, name='Current bid', value='test', inline=True)
await interaction.followup.send(content=None, embed=embed, view=self)
in button callback, error: unknown webhook
How can i save {} variables in json file?
I make it, but i've got this:
show code
def say(self,name: str, sub_module: Optional[str] = None):
with open(f'data/lang/{self.lang}.json', 'r') as f:
config = json.load(f)
if sub_module is not None:
return config[f'{self.module}'][f'{sub_module}'][f'{name}']
else:
return config[f'{self.module}'][f'{name}']```
and after:
```py
await ctx.respond(f"{lang.say(name='mute')}", ephemeral = True)
"mute": "{ctx.author} - admin"
where do you store the values????
which ones?
was selfbot support removed from pycord?
nothing to be sad about
selfbots are fun sometimes
are you doing selfbotting?
not rlly
i tried 2 times just for educational purposes. streaming status nothing that would abuse discord api

it's still in violation of their terms of service
whether you do anything with it or not
after i used that i figured out
Ignorantia legis non excusat
Traceback (most recent call last):
File "/home/catto/Documents/Network-Bot-Beta/bot.py", line 9, in <module>
from _global import (
File "/home/catto/Documents/Network-Bot-Beta/_global.py", line 17, in <module>
from cogs.n import NetworkGroup
File "/home/catto/Documents/Network-Bot-Beta/cogs/n.py", line 19, in <module>
class Network(commands.Cog):
File "/home/catto/.local/lib/python3.10/site-packages/discord/cog.py", line 238, in __new__
new_cls.__cog_commands__ = tuple(c._update_copy(cmd_attrs) for c in new_cls.__cog_commands__) # type: ignore
File "/home/catto/.local/lib/python3.10/site-packages/discord/cog.py", line 238, in <genexpr>
new_cls.__cog_commands__ = tuple(c._update_copy(cmd_attrs) for c in new_cls.__cog_commands__) # type: ignore
File "/home/catto/.local/lib/python3.10/site-packages/discord/commands/core.py", line 1263, in _update_copy
return self.copy()
File "/home/catto/.local/lib/python3.10/site-packages/discord/commands/core.py", line 1231, in copy
ret = self.__class__(
TypeError: BridgeSlashGroup.__init__() missing 1 required positional argument: 'callback'
I believe this is an error in the package
@bridge.bridge_group()
async def networks(self, ctx):
...
show the full code
That's full
I just wanna test the bridge and it occurred
how to do it in python if you write a message, they didn’t write anything in response, but if you put a question mark like type in this message, write the answer
write?
what you mean write
mylist = ["Нет", "Возможно", "Да", "Скорее да", "Скорее нет"]
elif text == "?":
send_message(user_id, random.choice(mylist))
how to do it in python if you write a message, they didn’t write anything in response, but if you put a question mark like type in this message, write the answer
that is, the answer to the message is given if the value is "?" at the end, and if "?" not at the end of the answer did not give
how to do it?
Question how would i go about getting the time tell the next cycle on a task loop from inside a command
or for that matter any tasks info

tasks.Loop.next_iteration
do variables created in a before_invoke exist during the invoke?
is there a way to handle interactions between but runs?
I think, no
when the bot isn't running, it doesn't receive interactions from Discord
No, because thats not how python works. :/
You could just make a function that is ran as the first thing in your command
i meant while the bot is up, to still have the ability to handle interactions from previous runs
why is my bot cant get guild by id?
if the interactions come from views, I think, you can do that somehow if you use persistent views
guild: Guild = self.bot.get_guild(guild_id), it is none
everything provided is correct

