#discord-bots
1 messages · Page 1156 of 1
i posted the code
It's about getting the content of it
.
Enable intents.message_content
And I told you 3 times what might be the issue....
where
If you don't read, that's your fault
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
still doesnt work
Did you even reinvited your bot with the correct scope
I have just noticed that if i ran a command and instantly run the same or any command again. It takes time to run the second command till the first one is completed. I dont want this to happen
It has always had the right scope
idk if it possible to do these with requests.post()
but I also readded
In that vase share more of the code, only those lines are not the root cause of your issue
Did not work
its basically to be able to use application slash commands
Im clearly doing something wrong here
What is your code now for the intents?
await bot.tree.sync(guild=discord.Object(id=int(GUILD)))
That's still not your full code 
Have you passed it in the bot object?
maybe I should put it under a class?
Like intents=intents
prefix = '!'
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix=prefix, intents=intents)
bot.synced = False
bot.remove_command("help")
@bot.event
async def on_ready():
await bot.wait_until_ready()
if not bot.synced:
await bot.tree.sync(guild=discord.Object(id=int(GUILD)))
bot.synced = True```
You do that in the main file only
You define bot only once, never twice
you don't, you can pass the bot in the cog class' __init__ dunder instead
set it as an attribute of the class, and use self.<the variable assigned> to access it
yes, I did
That's not how cogs work
https://discordpy.readthedocs.io/en/latest/ext/commands/cogs.html
See how they define bot and access it with self.bot below

https://solveforum.com/forums/threads/solved-pycord-discord-py-getting-403-forbidden-error-50001-missing-access-even-though-i-have-all-intents-permissions.618585/ I basically have the same error
WilliamD47 Asks: PyCord/Discord.py getting 403 forbidden error 50001 Missing Access even though I have all Intents & Permissions
I have this code for my PyCord bot,
from discord.ext import commands
import discord
intents = discord.Intents().all()
bot = commands.Bot(command_prefix='b/'...
How did you invite the bot?
Invite it with https://discord.com/oauth2/authorize?client_id=YOUR_BOT_ID&scope=bot+applications.commands&permissions=377957502016
Replace YOUR_BOT_ID with the ID of your bot and replace the permissions=377... to the permissions your bot needs.
Guys anyone here have hikari tutorial?
im tryna see if its possible to automate interactions with applications through slash commands
idk if its possible to do requests.get to get the variables to fill the payload then make the requests.post
payload needs: session id and data
Oh thanks
Hey how can i do so my bot would say "You are the 160th member"?
I want the bot to display st, rd, th behind the number
await message.send("you are the 160th member")
your welcome
nono not like that, in embed for welcome message
!d discord.Guild.member_count
property member_count```
Returns the member count if available.
Warning
Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be specified.
Changed in version 2.0: Now returns an `Optional[int]`.
it show 151 instead of 151st
can I prevent bot crashing if the network gone
I made a discord bot which shares reddit submissions randomly as an embed whenever the command is sent, can i make it such that it shares only images?
add a st to it... that depends on your string logic
yep ofcourse you can even just send the link and it will embed that
Just send the image link from API ig
i am also adding some other content in embed, so i cant share it as normal link
Put it on a VPS, even reputable cloud service providers will have network outages. Fortunately they’re good at fixing it up really fast because even a 10 minute network downtime could mean potentially millions of $ lost in revenue
Home networks aren’t as good as getting back up
then do what eggyinit said
Ya
is it possible to automate interactions with apps through slash commands
it seems all thats needed is to get session id and some variables to fill the payload for the requests.post
im just not sure about the syntax to try all these things
Yes, though I believe that’s against terms of service
keep = message.content.split(",",1)[0]
As Robin said, I recommend DigitalOcean for cheap and reliability Eggy, others may have other suggestions. If its just a case cause you turn your PC off, could always look into a RasberryPI but again, it all depends on your home network to.
Personally, I have a pretty reliable network so I used to host it on my RPI 4 before switching to AWS EC2. We still had network & power outages but we’re resolved swiftly
We don’t recommend heroku
As I work in AWS myself, I am actually tempted to switch over cause I know I could keep usage down and not rack up a bill in the 1000s lol. But DigitalOcean have always been just as good for smaller projects really, I am looking at some PIs myself soon for a cluster service.
AWS EC2 is not free lol.
T2 micro instances are free for 12 months
But honestly feels too low end
Ah cool! Have a family member who works there as well haha
Do NOT use AWS if you have no skillset with it, its an enterprise solution and I see it happen daily with people running bills into 1000s because they don't know what they are doing. I mean I just work with AWS tech, sorry my wording can be awful at times.
I would always recommend digital ocean as its very user/new person friendly, and very easy to just fire up a Linux VM with little effort.
how are bots able to respond to multiple users at the same time
i see mine can only handle the same command one at a time
Doesn’t AWS have methods to limit billing expenses?
What’re you doing in the function? Might be blocking
i do things in the on message
i dont use bot commands
i guess its obvious then
but im not sure replacing with botcommands makes a diff
Okay.. Can we see the code for the on message?
ok
No indeed. As Jammy mentioned, it’s an enterprise solution
Are these things supposed to be commands
Seeing all those splits makes me think you are implementing arguments this way
Using commands would remove all the manual parsing
Hello! I want to do a command that write an embed message like this https://gyazo.com/43af9a54d39500694f4ea46094e5dc37
When I write the command !sregler it just sends like this https://gyazo.com/936d31e20543a6ebc67a26efb070a6ab
the code:
https://www.toptal.com/developers/hastebin/babumelegi.py
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
You can only have one footer. If you set the footer multiple times, only the last one will be used
Ok thanks but how should I write the code if I want it like on the picture?
I asked this question earlier and did not got any response, i really need help with this.
The bot which i am working on does not respond to any other or same command unless and until the previous command is fully executed. I don't know why this is happening
Probably add it as one big description with newline characters (\n)
It's hard to tell without knowing what's going on in the command. Can you paste the code for it? It might be blocking
ahh thanks
Sure just a sec
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
this is one command
https://paste.pythondiscord.com/kuromuzuro
this is another
https://paste.pythondiscord.com/ujuderaxih
they are just code under the command
I can stream you the delay that is happening if you wish to
For the 2nd command, I'm guessing this part is blocking:
JavaServer.lookup('play.timepvp.in').status().players.online
you'll have to find a non-blocking alternative to this
As for the first command, I'm guessing it's all of the kitpvp...() methods
For which, again, you'll have to find a non-blocking alternative
hmm
I just dont understand about other commands like
for example,
The stats command i have enabled a guild cooldown of 5 seconds, even that is considered a command ran by the user when the previous command has fully executed
I know about creating a task in asynchronous programming. but dont know how to implement it here
You could try create_task, might be worth it
But the better option would be to find a non-blocking, asynchronous alternative to the JavaServer and kitpvp modules
the kitpvp module was created by me
it's a class which fetch data from a MySQL database
I can show you the class if you want to look into that?
Ah okay. How are you interfacing with a MySQL database?
I'm guessing that's where the problem lies
mysql connector - python
Can you send me the pypi page?
https://pypi.org/project/mysql-connector-python/ oh is it this?
yes
Well there's your issue
It's not asynchronous and blocking
You'll need to switch to an asynchronous mysql connnector
would it make a difference that when the bot starts, the mysql connection is made due to i create an instance of the class before hand (dont worry i close the database after the bot is stopped and the data is committed after 60 seconds)
No, you need to switch over libraries
Personally I can't recommend any good ones as I've never used mysql, but you might have luck asking in #databases for python async aiosqlite connectors
so like making the fetching of data asynchronous?
alright thanks!!
aiomysql should do the job
how do I send a message as a response to the user who ran the command?
no like
like this "replying to"
!d discord.ext.commands.Context.reply
await reply(content=None, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shortcut method to [`send()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.send "discord.ext.commands.Context.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") referenced by this context.
For interaction based contexts, this is the same as [`send()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.send "discord.ext.commands.Context.send").
New in version 1.6.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") or [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") instead of `InvalidArgument`.
ty
it tells you the Attribute error
#media-processing please
you really shouldnt use the internal session the bot class has
im pretty sure it passes your Bot token into a header for each request
? the internal session is Bot/Client.http.__session which can't be accessed anyways
need to use .http._HTTPClient__session for that iirc
this is cool
Discord PR staff: How the hell do we get people to get excited about the old discord API
Also discord PR: Just add a badge people will do anything for them
noone's gonna complain about slash commands now, cause badges are ✨ cool ✨
ik
how do i store data within my bot?
🗿 and they are not using that i forgot to include
...
does it need to be temporary or permanent
permanent
i legit thought u were actually reading the source
what's the data
i did a bit of googling and i'm to put the filename in .gitignore which is what i'm trying now
levels, warnings and so on
make a SQL db
i'll try that second
src of?
another thing u can use is mongodb
@shrewd apex
i am
yet I have installed it, how can I fix it?
I thought Discord added a new badge for badge hunters, but no it's for the bot 
huh? .gitignore dosent store stuff
yes but i can stop it from resetting everytime i run the bot
oh nais nais i won't disturb u
which is what it does currently
just dont use it, install dpy2.0 and use that
i disturb myself 🚶♂️
close discord tab and focus
if u want a permanent db either use sql based db like postgres aiosqlite
or if u don't wanna learn SQL us a nosql db like mongo
👍
and not JSON
how do I install it?
https://gist.github.com/Ash-02014/b6f57065f394b54f43666037ade38d32 here's a complete guide of how to install and use it
okay thanks
mongo
?
imagine mongo sheesh
what's wrong with it
go sleep
it's 7 something in uk og
that way everything is bad
some how or the other
ofcourse
how do i delete server template and create a new one
and send the url of the new one
I want to develop a bot that automatically bumps my server after the discord bumper time is over. I am very new to bot development , so the only solution currently i can think of is that i run the /bump command once and then let the bot reply to that msg with /bump in the specific time interval. So he keep on going... I dont know if its the efficient way. Could someone please guide me abit on that? Is there a specific function in the discord api?
@bot.event
async def on_message(msg):
username = msg.author.display_name
#if msg.author == bot.user:
#return
if msg.content == '/bump':
await msg.channel.send("/bump " + username)
use @tasks.loop()
I don't think slash commands just works by sending the command prefixed with slash...?
true
instead of that, how can i send the link of the existing server template?
so printing it wont work?
No
is there another way to run a command then
They works on completely different endpoints
You can send http requests to this route but I wonder if discord allows bots to run slash commands
Also most bot developers themselves ignore bots, even in gateway commands. So I don't think there's any way to do that
!d discord.Guild.templates
await templates()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gets the list of templates from this guild.
Requires [`manage_guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_guild "discord.Permissions.manage_guild") permissions.
New in version 1.7.
i used it but
Exactly the reason why bots can’t invoke the slash commands of other bots, so you can’t automate it
https://codeberg.org/SnowCode/auto-bump#:~:text=SnowCode%2Fauto-bump%3A A,automatically bump servers on Disboard. i found this repo that isdoing the same thing
[<Template code='gQ5USdenfeRFbUDW' uses=0 name='🂱🂶 Backup_AW' creator=<User id=999636884923883531 name='Meft' discriminator='6dedef10' bot=True> source_guild=<Gefefeild id=921366728016011324 name='eedefd🂶' shard_id=Nonefe chunked=False meefmber_count=469690>>]
@slate swan
That’s a self bot and against discords terms of service
That's a 2 years old code when gateway commands were active
help me
Choose the template you need the url for, and the object returned is a discord.Template class
a server can only have one template
how do i choosee it
so there is a way but against tos
has anyone replicated the Dyno's action log? 
Uhm the dpy's docs says it returns a list of Templates. Well if that's the case just do templates_list[0]
…yes
There used to be a way... which was against tos..
will it still print [<Template code=dieewifbefebfeifew>]
There are still more ways but yeah they all break tos one way or other
i want it to print https:template.f//isKJnifnI6
That's a representation of class. If you use it's attributes you can get whatever you need out of it
For code, you need to template.code
!d discord.Template.code
The template code.
niceeeeeeeeeeeeeeee
And to get url, prefix https://discord.new/ before the code
okay
That’s out of my expertise, sorry
i’m sorry, what?
what are you even trying to do
i think you’re in the wrong channel bud.
a better place would be #965291516031549500 /the discord developers server itself
why are you trying to read the raw responses and requests tho
ok so after recommendations about rate limits it's coming from replit, I hosted my bot on google cloud virtual machine and got this error
you are probably doing something which is making a lot of reqs
!paste mind showing your complete code
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
!d discord.Member.avatar
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar "discord.User.avatar")
avatar_url has been removed
!d discord.Member.avatar.url
!d discord.Asset.url
property url```
Returns the underlying URL of the asset.
Avatars are now an Asset too
i can show you my complete project sarth but i won't show it here because the code is very very long and might contain sensitive parts i don't want to share. shall i dm you and add you to the github repo so u can see it?
user.avatar.url to be more specific
it's been some time i'm thinking to show the whole project to someone experienced that could give me some tips to clean/improve the structure so yeah
That's some issue with your image processing. #media-processing would be a better place for this
I don't know anything about PIL
Also you can just use Asset.read() function instead of making separate requests to download the image
Is this really possible?
yes
yeah sure
Probably yes but it's just going to do everything twice
Uhh my keycap just broke 💀 rip
its okay to do that for a REST based bot or a bot which only uses message commands, but never try it with an interaction bot
If I made a bot with 5 features, would you recommend me to use cogs (5 files) or just smash them all into one ugly file?
depends on what the commands are, i categorise commands usually
but still, 5 beautiful files, or one ugly smashed file?
Depends. Suppose you have 5 commands, help, nukeserver, giveadmin, uwu, game, I'll categorize them accordingly, like help being a utility command, nukeserver and giveadmin are.. uh... critical commands I'd say, and uwu and game are just basic fun commands. Hence 3 cogs
But still cogs are recommendable over just one file, with lets say 40 commands.
That's completely subjective. Some people like to smash all 1000 lines in single file and others like to make a cog for every command. Do whatever you like. Though I'd recommend more than ~10-20 commands should be into cogs
for 40 commands yes, but i wont do a extension file for just 5 commands if they aint too long
also, cog != extension, you can create cogs in your main file itself in case categorising commands is your only need
can i make my bot automatically send a message and @ someone each hour?
!d discord.ext.tasks.loop yes
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
thx
you can use this decorator on a coroutine, the coroutine will get triggered after each mentioned time
hey i cant get slash commands to work, it says import "discord_slash' could not be resolved,
how can i fix this, for reference i did pip install discord-slash commands or whatever the pip was
from discord_slash import SlashCommand, SlashContext
from discord.ext import commands
client = commands.Bot(command_prefix='!')
@client.command(
async def ping(ctx):
await ctx.send('Pong!')
stop using 3rd party libraries, just use discord.py master or a fork instead
what are those?
discord.py is an actual app?
if i move all my code into it would i need to import any discord related modules
so what about my imports are 3rd party?
https://gist.github.com/Ash-02014/b6f57065f394b54f43666037ade38d32 this is a guide on how you create app commands using discord.py
the discord_slash library.
!D discord.ext.tasks.Loop
class discord.ext.tasks.Loop```
A background task helper that abstracts the loop and reconnection logic for you.
The main interface to create this is through [`loop()`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.loop "discord.ext.tasks.loop").
@slate swan it still doesnt work
you didnt even read the gist, you are still using the same library
i did not read the gist to be honest
you know, thats my bad, i hate reading, ill hit the books and actual understand what u sent
Can anyone help me with setting up errors for using commands in the wrong channels?
trying to host my bot on heroku and it's saying "App not compatible with buildpack" with my buildpack being python and the bot being coded with it, any idea how to fix this?
@tree.command(name="hierarchy",description="Get a list of staff members.",guild = discord.Object(id=guildID))
async def self(ctx: discord.Interaction):
channel = ctx.guild.get_channel(998715594809548850)
roles = {
"Owners":998412738109898812,
"Co-Owners":998413729370755093,
"Admins":998414999590547456,
"Moderators":998414468570681405,
"Developers":998415323621503078
}
embed = embed=discord.Embed(title="Staff Members", description="", color=0x2f3137)
for i,v in roles.keys():
members = []
for i2 in (discord.utils.get(ctx.guild.roles, id=v)).members:
members.append(i2.mention)
listOfMembers = members.join("\n")
embed.add_field(name=f"{i}",value=f"{listOfMembers}",inline=True)
await ctx.response.send_message(embed=embed, ephemeral=True)```
Any ideas?
no line number
roles.keys() will return just the keys of your dict as a list
!e
my_dict = {
"hello": "world",
"some key": "some value",
}
print(my_dict.keys())
@sick birch :white_check_mark: Your 3.11 eval job has completed with return code 0.
dict_keys(['hello', 'some key'])
makes much more sense. thank you
If you want both key & value, try .items()
got it 👍
!e
my_dict = {
"hello": "world",
"some key": "some value",
}
for k, v in my_dict.items():
print(f"Key: {k} | Value: {v}")
@sick birch :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Key: hello | Value: world
002 | Key: some key | Value: some value
thats actually what i was going for, but recently came back to python so must've got them muddled up
Common issue, no worries
Also from what you said about "no line errors", I think you should get that fixed. I'm guessing the issue is that in your error handler, you're just doing something like print(e), but a better method would be to either re-raise it (raise e), or use the traceback library to print_exc()
Ah. Thank you for the tip
any way to have a set option for d.py 2.0 slash commands? for example, one parameter has either "yes" or "no"?
would this work? last time i used the top bit of code was a bit ago and i used a different way of coding my bot
put the if statement before the list
in between the async def and list
thanks
Use typing.Literal
Literal["yes", "no"]
care to link me a doc or something? been searching for ages
I’ll see if I can find it
where would i put this? in the decorator?
As a typehint for the parameter
async def self(ctx: discord.Interaction, Literal["yes", "no"]):?
async def self(ctx, option: Literal["yes", "no"])
not sure what it means
not defined
from typing import Literal
ah
is discorx.ext differend from discord, i forgor
wdym
Can anyone help me with setting up errors for using commands in the wrong channels?
i'm a little bit of an idiot and forgot what the difference is
they are different modules. discord.ext is part of discord tho
@torn sail Can you help me?
yeah sure, do you already have a check for the channel?
do i need to do the import commands, task thing as well or does importing discord import the whole thing
Nope.
you need both
thanks
Legit just need source loll
how do you want the check to be applied? all commands, some commands, etc
so if a user executes the a cmd in the wrong channel it replys with what i want it to say
im not too good with handling errors lol
@torn sail slash options worked. Much appreciated 🙌
!d discord.ext.commands.check
@discord.ext.commands.check(predicate)```
A decorator that adds a check to the [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or its subclasses. These checks could be accessed via [`Command.checks`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks").
These checks should be predicates that take in a single parameter taking a [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure") exception is raised and sent to the [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event.
If an exception should be thrown in the predicate then it should be a subclass of [`CommandError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError"). Any exception not subclassed from it will be propagated while those subclassed will be sent to [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error").
@torn sail So how would i use this?
I would make the predicate raise a custom error and handle it in an error handler
Either typing.Literal or from typing import Literal
i'm handling err commands.errors.MemberNotFound, and do this with on_command_error. I have 2 this handlers. And when im have this error, my 2 handlers working. How to handling errors like a normal people?
like this
class WrongChannel(commands.CheckFailure):
pass
def check_channel(ctx):
if ctx.channel.id not in [2329834234, 234723423]: # some channel ids here
raise WrongChannel()
return True
@commands.command()
@commands.check(check_channel)
async def command(ctx):
...
Sorry.. could you be more clear? Not sure if I'm understanding
crazy.. has it changed from 1.0 to 2.0?
add_roles(...)
add_roles
bruh wow
It's plural, you can add multiple roles at once which is why
yeah makes sense
idk how to describe this... sorry
ok, i wanna to handle commands.errors.MemberNotFound repeatedly. How can i do this?
is there a better way of doing this? i have the large stupid and cant get it to work. i tried this @discord.ext.commands.is_nsfw() but i cant figure out how to use this
How exactly would that work? There's no point in handing the same command multiple times
So you only want a certain command to work in an NSFW-marked channel?
if you dont use the decorator you can use channel.nsfw within the command which returns a bool
only works for text channels
i think
@torn sail ```class WrongChannel(commands.CheckFailure):
pass
def check_channel(ctx):
if ctx.channel.id not in [998928038047780935]:
raise WrongChannel()
return True
@commands.command()
@commands.check(check_channel)
async def command(ctx):
channel=discord.Embed()
channel=discord.Embed(title="🤖 ERROR 🚫",description=f"Command used in the wrong channel {ctx.author} !",color=0xffff00)
await ctx.reply(embed=channel)``` when running cmd in wrong channel no error is raised
yep
originally the code was just this, but i want to make it only work in my nsfw channel
So something like
def is_nsfw():
async def predicate(ctx: commands.Context):
return ctx.channel.is_nsfw()
return commands.check(predicate)
@bot.command()
@is_nsfw()
async def nsfw_only_command(...):
...
@bot.command()
@is_nsfw()
async def another_command(...):
...
You can reuse it in as many commands as you want
Just use this @jovial dock if ctx.channel.id==998928038047780935:
easy lol
It will only excute if cmd is run in the right channel
do you know if there is there any different between channel.nsfw and channel.is_nsfw()
@torn sail (sorry for the ping)
hmm do you have a error handler
Aside from the fact that it doesn't exist? No
!d discord.TextChannel.nsfw
If the channel is marked as “not safe for work” or “age restricted”.
thanks for the help
ok i guess it does exist
Nah i have 0 clue on how to even use error handling
did u add the command to the bot?
yes.
ok just making sure lol
When i tried in the wrong channel no error was raised.
oh wait
The command just didnt work loll
wait so how do you want it to work
So if a user executes are certain command in the wrong channel it responds with for example f"ERROR {ctx.author} Command used in wrong channel !"
ok then you need to apply @commands.check(check_channel) on all the commands you want it on
and then you need to make a error handler
Mind showing me??
sure
async def on_message_edit(before, after):
await before.channel.send(
f'{before.author} edit a message.\n'
f'before: {before.content}\n'
f'after: {after.content}'
)```
is there a way to fix this? as shown before i have the large dumb and cant do basic troubleshooting because i watch too many tutorials
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, WrongChannel):
await ctx.send('Wrong channel')
else:
raise error
Okay ty! And one last question !
i would like to point out that raise error is very important
yes
How would you set up 2 diff commands that raise a error if your missing roles? Without it getting confused
@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
This check raises one of two special exceptions, MissingRole if the user is missing a role, or NoPrivateMessage if it is used in a private message. Both inherit from CheckFailure.
You can catch those errors
Btw code you sent me didnt seem to work.
explain more with "not work" and send the code you have so far
@bot.event async def on_command_error(ctx, error): if isinstance(error, WrongChannel): await ctx.send('Wrong channel') else: raise error
No error is raised when i run the cmd in the wrong channel.
show how you use the check on the commands
Heres for missing roles
@bot.event async def on_command_error(ctx, error): error=discord.Embed() error=discord.Embed(title=f" 🤖 ERROR 🚫 ",description=f"{ctx.author} premium role is needed to run this command !",color=0xffff00) await ctx.reply(embed=error)
I need a smiliar one for wrong channel if you understand.
you should make sure the error is the correct error
if isinstance(error, commands.MissingRole):
it works perfectly fine though
and then you can use elif isinstance(error, WrongCHannel):
whats the use of ^
it ensures the error raised is for missing a role
Checks what the error actually is
otherwise every non related error will also send that
So thats why when i misspell the cmd it still sends that
yep
make sure to add
else:
raise error
Invalid syntax
this part should follow the if statements
Still throws a error
show code
@bot.event async def on_command_error(ctx, error): if isinstance(error, commands.MissingRole): else: raise error error=discord.Embed() error=discord.Embed(title=f" 🤖 ERROR 🚫 ",description=f"{ctx.author} premium role is needed to run this command !",color=0xffff00) await ctx.reply(embed=error)
the else should be after the stuff in the if statement
if isinstance(error, commands.MissingRole):
# do stuff
...
else:
raise error
Oh okay
By the way, raise ... acts as sort of a return so nothing after it would run
yeah
async def on_message_edit(before, after):
await before.channel.send(
f'{before.author} edit a message.\n'
f'before: {before.content}\n'
f'after: {after.content}'
)```
when someone or my bot sends a link with an image and it doesn't instantly load, it will send a message thinking it was edited, can i fix it or will it just have to be like this
Bruhhh
@torn sail nope
I hate discord.py
Do you mind sending me just the complete code???
You can check to make sure that before and after don't have attachments included
We can't spoonfeed you, sorry
i can send you a full example which you can fit into ur code
i really cant be bothered to sit here and wait dont have much time tbh
can ya make it in ooga booga terms?
Basically check if the message before and the message after doesn't have any attachments (links, images, embeds, etc)
i need spoonfeeding im not really here to sit down and waste time i just need the code and im gone.
if not (before.attachments and after.attachments):
...
thanks, is there a command for the discord.py docs?
That would help 100% !
Then unfortunately this isn't the right server for you
!docs
class WrongChannel(commands.CheckFailure): # making our own custom error
pass
def check_channel(ctx):
if ctx.channel.id not in [834823423423423, 2323423423423]: #channel ids
raise WrongChannel()
return True
@bot.command()
@commands.check(check_channel)
async def random_command(ctx):
...
@bot.event
async def on_command_error(ctx, error):
# our error handler
if isinstance(error, WrongChannel): # checking if this is the error we want
await ctx.send('That was the wrong channel')
else:
raise error # re raise the error so we don't eat up every error
make sure that you understand what is happening in this
Ill make sure i have a read up online on this
But im only in a rush thats all lol and thankyou
the docs might also have helpful stuff too
so what does the randomchannel do?
where do i import this? i keep seeing that it wants to come from email instead of discord, or does message not exist
@torn sail
At the (check_channel)
im not sure i see that but if you mean random_command thats just an example function for the example command
if self.client.top_role < member.top_role:
embed = discord.Embed(description = f'{author.mention}**stop**')
await ctx.send(embed = embed)
with this⬆️ command dont working. How to check this
Yeah i did and okay lol
message needs to be the actual message. What's this inside of? an on_message? A @bot.command()?
@bot.event
async def on_message_edit(before, after):
if not message.attachments:
await before.channel.send(
f'{before.author} edit a message.\n'
f'before: {before.content}\n'
f'after: {after.content}'
)```
this is happening
if it doesn't load in immediately then it will detect it as a change so it sends that message
well yeah there's no such thing as message
you'll want to check both before and after
there isn't? all the stuff i see on how to fix these things shows message.____ as a thing
Yes, though message is usually just a substitution for your discord.Message instance
File "C:\Users\Clicks\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 456, in _run_event
await coro(*args, **kwargs)
File "c:\Users\Clicks\Desktop\Timmy (smile)\bot.py", line 383, in on_message
@commands.has_permissions(manage_messages=True)
AttributeError: 'str' object has no attribute 'contains'```
what??????
@client.command(aliases=['clear', 'prune'])
@commands.cooldown(1,10,commands.BucketType.user)
@commands.has_permissions(manage_messages=True)
async def purge(ctx, amount=11):
amount = amount + 1
if amount > 101:
await ctx.send('Can not delete more than 100 messages at once!')
else:
await ctx.channel.purge(limit=amount)
await ctx.send('Cleared the messages requested by {}'.format(ctx.author.mention))
await ctx.message.delete()```
Can we see the full error?
Looks like parts of it are chopped out
that is the full error
Hmmm.. errors are usually much longer. Are you sure?
Because what the error is saying and the code you sent don't seem to match up
I re-launched vs code and it seems to fix the problem
I dont have the word "contains" ANYWHERE in my code
Strange. Maybe VSCode is just being strange
At least the restart fixed it. Hopefully it doesn't happen again
Yeah I guess so
@client.command()
@commands.is_owner()
async def blacklist(ctx, member: discord.User):
embed = discord.Embed(title = "User Blacklisted", description = f"A user was added to the blacklist", Timestamp = ctx.message.created_at)
embed.add_field(name = "Member Blacklisted:", value = f"{member.name} : {member.id}")
client.blacklisted_users.apped(member.id)
data = read_json("blacklist")
data["blacklistedUsers"].append(member.id)
write_json(data, "blacklist")
await ctx.send(f"**{member.name}** | **{member.id}** has been **__BLACKLISTED__** from using Timmy")```
no response
oh wait, im dumb
nvm
nvm the nvm
it doesnt work, no errors, no nothing
async def called_once_a_day():
message_channel = bot.get_channel(999841816809582642)
print(f"Got channel {message_channel}")
await message_channel.send("")```
is there a way to also get my friend's Discord profile picture every 15 minutes and send it along with the message?
every 15 minutes it @crimson bridge my friend and i want it to also send his pfp
sorry whoever i @ ed
You can get their profile picture using discord.Member.avatar
!d discord.Member.avatar
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar "discord.User.avatar")
make sure you actually use the instance, not the class
Try:
@tasks.loop(minutes=15)
async def called_once_a_day():
message_channel = bot.fetch_channel(999841816809582642)
user = await bot.fetch_user(yourfriendsidhere)
await message_channel.send(f"{user.mention} , {user.avatar_url}")
sounds like smart person talk to me
thanks, i now can annoy my friend more efficently
bot.fetch_channel() has to be awaited
it's also called every 15 mins, idk if that's intentional?
very
in the decorator, you can use the aliases keyword argument, it takes an iterable
i like your funny words magic man
What to do?
Its replit
Yes
Yes
Wait giving you replit multiplier link
How to do that?
@languid wagon see dm
I share replit link
Yes
why is that?
not true, IDs are related to the time which the snowflake was created, so it can be random
they generate like tokens with there timestamp right
kinda
yeah
hehe bits go brrrrr
do global slash commands still take an hour to register?
they should be instant now
okie ty !
👍
yeah
why are new ids getting a new digit? running out of possibilities?
and what makes the ids longer?😅 😭
im not sure what youre referring to😅
ah cuz unix timestamps start from jan 1970 and its all in seconds or?
im not very familiar with unix's timestamp system
can anyone send any gh repos which use the official discord.py library for implementing slash commands?
yep
https://gist.github.com/Ash-02014/b6f57065f394b54f43666037ade38d32 if you just want examples this gist got decent ones
true, but most of the forks suck 🚶♂️ including pycord
yeah i am reading that but im a little confused bc in the cogs example its constructing the bot and running it in the cog
yeah its totally possible to do that as well, cogs can be placed in an extension file or the main file itself
ohh yeah i forgot abt that
for an extension file you would be bot.add_cog inside a setup function, whereas in the main file you can do add_cog directly
from what i understand in the docs, you have to use @app_commands.describe() to set the params for the slash commands, but how do i specify the data type of them?
the error is explainfull, the aiohttp session must be initialized inside an async function
in the library i used before, you could specify the variable name, display name, type, and whether it is required or not, but here i can only seem to specify the variable and display name
you typehint the arguments
oh ok
and how do i specify whether its required or not
examples/app_commands/basic.py lines 70 to 75
@client.tree.command()
@app_commands.describe(member='The member you want to get the joined date from; defaults to the user who uses the command')
async def joined(interaction: discord.Interaction, member: Optional[discord.Member] = None):
"""Says when a member joined."""
# If no member is explicitly provided then we use the command user here
member = member or interaction.user```
arg: typing.Optional[<type>]
``` or ```py
arg: <type> | None
``` works too if you're on 3.10 or if you ```py
from __future__ import annotations
Hi all
hi, my name is All
that's obly for adding descriptions to the arguments, read carefully
sheesh did I forget to update the gist brb
@commands.Cog.listener("on_message")
async def message(self,message):
api = os.environ['key']
message = message.content
analys = perspective(message,api)
toxicity = analys.toxicity()
await message.channel.send(f"toxicity of your message is **{toxicity}**")
How to fix this error?
you are doing message = message.content so
Oh
I need to change the variable?
Oh ty
How can I make my bot not listen to bots messages?
add a if message.author.bot: return at the top of your listener
why even store it at that point lol
idk
I added hybrid commands examples to the gist atlast 
https://gist.github.com/Ash-02014/b6f57065f394b54f43666037ade38d32#hybrid-commands
lol, i hate hybrid commands
or atleast dpy's implementation
im trying to rewrite the bots main file to make it work with d.py v2, but im getting this error and have no idea what to do https://hst.sh/uvojokixaj.py
i followed this example https://github.com/Rapptz/discord.py/blob/dc50736bfc3340d7b999d9f165808f8dcb8f1a60/examples/advanced_startup.py
i know that but like for the main function
for asyncio.run(main()) i cant await that cus its not in an async function
yeah
why are you sending the toxicity EVERY SINGLE MESSAGE
Guys I'm getting a bit error log that starts with
2022-07-22 09:46:28 WARNING discord.http We are being rate limited. POST https://discord.com/api/v10/channels/855852976630923274/messages/999975711190306836/crosspost responded with 429. Retrying in 1167.26 seconds.
anyone knows where this come from?
I do have Intents included like this:
intents = disnake.Intents(messages=True, members=True)
bot = commands.Bot(
command_prefix=".",
intents=intents
)
bot.add_cog(Main(bot))
``` But guild.members is completely empty, I can't even get the thumbnail (guild icon) or any data at all. ?
not that, I migrated it on a virtual machine on google cloud
where are you getting data
then it's the first variant
because you have only messages and members intents
I need others?
@commands.command(help="Get information about server", aliases=["serverinfo"])
async def server(self, ctx: commands.Context) -> None:
"""Shows you information about this server."""
guild = ctx.guild
offline_members = 0
online_members = 0
print(guild.members)
for member in guild.members:
member: disnake.member.Member
if member.status != disnake.member.Status.offline:
online_members += 1
else:
offline_members += 1
embed = Embed(
title=guild.name,
colour=COLOR,
)
embed.set_thumbnail(guild.icon if guild.icon else 'https://cdn.discordapp.com/embed/avatars/1.png')
embed.add_field(name="Total Members", value=guild.member_count, inline=False)
embed.add_field(
name="Members Status",
value=f"⚪ Offline: {offline_members}\n🟢 Online: {online_members}",
inline=False,
)
await ctx.send(embed=embed)
how else do you think you would be able to acess a server's icon
intents = disnake.Intents.default()
intents.members = True
``` something like this would work
But I CAN get the icon without any Intents passed
ah... let me try
that's what you think, but when you dont pass any intents, discord.Intents.default() gets passed.
remember to check the members intent on the dev portal too
that would raise an error
It totally worked. thanks 🎉
what's your code that did this
any task? anything in on_ready?
..?..
i mean, for every message that's sent, you reply
which is kind of annoying
https://paste.pythondiscord.com/negawanona
this is the error logs
the code that did this is bot.run(token)
i have no clue about where this come from
I have made change in it I just made that for startup ;-;
How do I make the time I get from user.joined_at or user.created_at a time stamp?
they looks like:
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
That worked. thanks 
Hey, I've got a bot in py-cord. I have an interaction and want to respond to it twice, but I get an error ```
discord.errors.InteractionResponded: This interaction has already been responded to before