#discord-bots
1 messages · Page 699 of 1
It says…
maybe commands.errors.CommandNotFound is enough
kk
Hey
!d discord.ext.commands.errors.CommandNotFound
exception discord.ext.commands.CommandNotFound(message=None, *args)```
Exception raised when a command is attempted to be invoked but no command under that name is found.
This is not raised for invalid subcommands, rather just the initial main command that is attempted to be invoked.
This inherits from [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError").
You can exclude the .error too
Can I get an example use of commands.PartialEmojiConverter?
!d discord.ext.commands.CommandNotFound
exception discord.ext.commands.CommandNotFound(message=None, *args)```
Exception raised when a command is attempted to be invoked but no command under that name is found.
This is not raised for invalid subcommands, rather just the initial main command that is attempted to be invoked.
This inherits from [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError").
seems like it
!d discord.ext.commands.PartialEmojiConverter
class discord.ext.commands.PartialEmojiConverter(*args, **kwargs)```
Converts to a [`PartialEmoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.PartialEmoji "discord.PartialEmoji").
This is done by extracting the animated flag, name and ID from the emoji.
Changed in version 1.5: Raise [`PartialEmojiConversionFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.PartialEmojiConversionFailure "discord.ext.commands.PartialEmojiConversionFailure") instead of generic [`BadArgument`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BadArgument "discord.ext.commands.BadArgument")
@lunar quail
give the full path
I have already read the docs
It apparently doesn't any arguments in __init__()
And type hinting it doesn't seem to work either
commands.Greedy[commands.PartialEmoji] seems to work tho
is there a way to log the timeout feature yet????
Try making an instance
if message.author != client.user:
try:
await bot.process_commands(message)
except discord.ext.commands.errors.CommandNotFound:
embed = discord.Embed(title="Command not found", description="Use a!help to find all commands.", color=0xFF0000)
message.channel.send(embed=embed)```
If there is no event for it u can read audit logs
How would I do that
theres no event for it yet
any idea why this isn't working?
no errors
What is not working? Like other commands are not working is on_message not working is the bot completely unresponsive?
Sending your full code will be helpful
my code will scar you for life, but its here https://paste.pythondiscord.com/imasevapej.http
I checked, u can use on_member_update
its on_message
Oh yea
my code runs perfectly, it even runs the commands but the except doesn't work
doesn't send the command not found
Check this out
It’ s how you can get a set of all commands
Also better way to make error handlers is to do it in on_command_error event
You should have told me that the code was about a porn bot. I almost opened it in my family computer 
Also
At this point
Don't use on_message
Instead use the listener
@slate swan
hm
@bot.listen("on_message")
async def check_if_contains(msg):
...
No
You don't have to process_commands here
What does handling errors have to do w this? I am just helping him cut an additional step to clean his code.
🤔
This is not how you do it
Then why did u tell him to use the listener
^
this'll be better -> if not(message.author == client.user): ...
*This was an reply to an deleted message
Why the ()
that should work exactly the same tho
Yes dw, ur way is good, idk why they are overcomplicating
Well lol
main.py:234: RuntimeWarning: coroutine 'Messageable.send' was never awaited
ctx.send(embed=embed)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
nvm
typo
& didn't read the error
!paste
someone gimme a working alternative for https://paste.pythondiscord.com/cirajalaju.sql
you know that this is useless cuz it will run only when the bot goes online?
you need it to run allways?
on_ready is called when the bot goes online so it is when the it start
yes
but it is useless cuz you count the guild of your client and that value will update everytime the bot joins a guild
but I need a alternative cuz on_ready is annoying and sometimes doesn't work 4 some reason
never had that problem but there aren't alternatives on on_ready
well fuck
How would I check if a user has a role?
!d discord.Member.has_role
mh it was the check for the command :L you have to get the list of the user roles and check if your role is in that list
If role in member.roles
Btw u can get servercount by doing len(client.guilds)
I use disnake
dpy is not mantained
me too
Never heard of hikari
So far so good
Hello, can anyone tell me what is:
Message intents
intents
!d discord.Intents
class discord.Intents(**kwargs)```
Wraps up a Discord gateway intent flag.
Similar to [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions"), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.
To construct an object you can pass keyword arguments denoting the flags to enable or disable.
This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").
New in version 1.5...
I’ m guessing it allows u to use on_message event
role = ['Staff', 'Host']
if role in member.roles:
#stuff
would this work?
No
Again this thing lol. No it doesn't work
You check if a list is in a list which is not possible in python
Wouldnt it check if that list object is in the list
use split on the list and it should be possible
?
nvm
Lmao
yeah but let's make an example the member has only one role, it will check if the string "staff, host" is in the list with one element
otherwise if the user has more roles and you convert the list of roles into a string you will check if the string "staff, host" is in the list of roles which is a string
you won't get if the user has that role
the best way is to iterate through one list and check if the role iterating is in the list of member roles
Lmao I was tryna help
ik
someone give me ideas how the fuck am I supposed to make this send messages always on the channels https://paste.pythondiscord.com/ehotapofag.sql
rn it only starts if a message is sent
and if on_ready doesn't work & doesn't send the message
it doesn't start so this sucks
Wdym?
You want to send message every x amount of time?
always what?
well its not
Wdym always
it needs a trigger
infinetly
You can use a task
something that make it send
on_ready should send a message which triggers on_message and on_message starts the loop
but it doesn't sometimes
and that breaks the whole damn bot
No bro lmao just use a task
roleIds = [849354245894963201, 849354245894963201]
for role in member.roles:
if role.id in roleIds:
#do stuff
break
Ur gonna get ratelimited this way
nah
because the on_ready event is triggered when the bot comes online to discord, but bot functionalities aren't callable yet
the transaction is too instant
Id rather iterate through shorter list
and it is based on the host connection
that's why sometimes work and sometimes doesn't work
Use a task
example
Docs
link
ok cmon
!d discord.ext.tasks.loop
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, loop=...)```
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/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
Here
!discord.ext.tasks
how am I supposed to make that work if it can only be triggered for some channels
Send it only in those channels
its supposed to be triggered when someone uses a!start or if thier channel is already stated
wait are you making a raid bot? lol
no
Start the loop when someone uses a!start
Autoporn bot
bruh hahaha
Lmao
btw yeah you have to use tasks, check some video on youtube they will explain how you use it you seems a lot confused
but it also needs to be started when the bot comes online, only for the channels that have a file tho
Well
Start it then
Make sure you use this , or no botlists will like to add your bot
!d discord.ext.commands.is_nsfw
@discord.ext.commands.is_nsfw()```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that checks if the channel is a NSFW channel.
This check raises a special exception, [`NSFWChannelRequired`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NSFWChannelRequired "discord.ext.commands.NSFWChannelRequired") that is derived from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`NSFWChannelRequired`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NSFWChannelRequired "discord.ext.commands.NSFWChannelRequired") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure"). DM channels will also now pass this check.
task starts automatically and they don't depend on on_ready
so they will work even due to connection problems
You can start it in on ready but it aint necessary
can I delay it like 1minute
yes
Yes
so it works better even on slow connections
Hm
check it on youtube
aka my romanian vds with 200ms normal ping
Use the decorator instead , it's better to make your code clear
and managing the exception
i'm going to run out of tobacco and i'm working so I can't go buy it lol
I'm sad 😦
😂
What's happening here?
my code is not supposed to be seen by anyone so idc if its a mess
Ur missing ()
thanks.
why do ppl remove the help command?
To make their own
cuz its ugly
cuz it is in english and it's ugly xD
Subclassing exists
even tho im confused abt how my own code works sometimes lol
Wait
yeah by subclassing you create your own but you have to say to the bot that you're going to use your own help command
Subclassed one , doesn't look ugly to me
are there any working code samples of the new timeout feature or is there still not a library for it yet?
disnake has it already
Disnake library implemented it
!d disnake.Member.timeout
await timeout(*, duration=..., until=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Times out the member from the guild; until then, the member will not be able to interact with the guild.
Exactly one of `duration` or `until` must be provided. To remove a timeout, set one of the parameters to `None`.
You must have the [`Permissions.moderate_members`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.moderate_members "disnake.Permissions.moderate_members") permission to do this.
New in version 2.3.
could you link me it
and pycord too iirc
yep thanks
i don't understand why you should use it btw
Do you have to import disnake?
Lmao timeout just made mute command useless
I mean, ban is more satisfying xD
Nope , it's a library you use instead of discord.py
at least you don't need a role to mute people any more xD
So I have to rewrite my whole code if I switch? @slate swan
Yes, and storing unmute date in db
Nope, disnake is a fork of discord.py
Not rly, just replace all discord’s with disnake
So everything I've written here will still work?
Not really
Just make your according to the v2.0 of discord.py and replace discord with disnake everywhere
Probably yes
Things like .avatar_url have changed
install it from pip lol
…
Your editor name?
fair enough lol
maybe I should upgrade my disnake even i thought i will not use that feature for my bot lol
sure
Slash commands etc exist
what do i put instead of the *
Ah
everything after * are kwargs
i see
!e
def timeout(*, duration): return duration
print(timeout(duration=10))
so it would be user.timeout(args go here)
@boreal ravine :white_check_mark: Your eval job has completed with return code 0.
10
please im losing my mind
???
@boreal ravine
yes
The duration argument is type Union of float or deltatime, until needs a datetime, if you use duration you have to set None to until and the opposite if you use until
Why is commands.Bot named client and interactions.Client is named bot
is there a error somewhere in this code? ```py
for guild in client.guilds:
for channel in guild.channels:
if os.path.exists("home/bot/adx/autoporn"+str(guild.id)):
with open("autoporn"+str(guild.id)) as file:
if file.read() != "enabled":
os.system("rm -r home/bot/adx/autoporn"+str(guild.id))
if os.path.exists("home/bot/adx/channel"+str(guild.id)):
with open("autoporn"+str(guild.id)) as file:
if len(file.read() <= 5):
os.system("rm -r home/bot/adx/channel"+str(guild.id))
if os.path.exists("/home/bot/adx/channel"+str(guild.id)) == True:
file = open("channel"+str(guild.id), "r")
if str(channel.id) == file.read():
file.close()
embed = discord.Embed(title="> __Channel inactive__", color=0xFF0000)
embed.add_field(name="Reason for inactivity", value="Restart by developer", inline=False)
embed.add_field(name="Note", value="Small bug fixes || Added new categories", inline=False)
await channel.send(embed=embed, delete_after=60)
break```
remember to do that or it will run to an error
fuck
i installed discord interactions but vscode wont work as long as i have it imported. (Python 3.9.9 and 10.1). But on 3.60it sayhs discord isnta module.
i want to make a voting command
in which a user can vote for a member and it gets logged and it resets every month.
Any idea how to make it ?
?
How can I check if a message has a mention
Just store votes for every member and reset every month
you will need a loop task that every month restores the values
message.mentions
I dunno i was following a discord-interactions tutorial and i did that
oh
can i use json data base for this ?
Try using disnake
So like does this only apply if it’s only a mention or contains a mention with words and stuff
What?
Yeah I think
No pls
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'User' object has no attribute 'timeout'
@boreal ravine
Well it is not suggested tho
Are there threads. This chat is crowded lol
This is a list of mentions in the message
um why ?
!d discord.Member.timeout
A fork with interactions ect.
i just need to store info for 1 month
!d disnake.Member.timeout
Nope , but you can always use #❓|how-to-get-help to get a help channel for your own
await timeout(*, duration=..., until=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Times out the member from the guild; until then, the member will not be able to interact with the guild.
Exactly one of `duration` or `until` must be provided. To remove a timeout, set one of the parameters to `None`.
You must have the [`Permissions.moderate_members`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.moderate_members "disnake.Permissions.moderate_members") permission to do this.
New in version 2.3.
@hybrid fjord
Just use mongo or something
it must be a member object
Ah.
i just know json tbh
mongo uses a json format
@boreal ravine it returns missing permissions even though i've given the bot Administrator permmisions
that db stinks, don't
?
and the Moderate Members permission
Wanna talk about NoSQL? lol
who did you try to timeout?
not a good idea to use nosql in a bot environment
You tried to timeout the owner of the server? lol
U can if It’ s a small project for urself
Why is that
better to do it the good way the first try
it doesn't really matter..
NoSQL can be a mess if you don't know it
nah ive given my alt administrator perms and the top role just in case i lose this account and i was tryna timeout it lol
It’ s not too hard to understand
just use Sqlite if it's a small/medium sized bot tbh
i mean theres nothing wrong with using mongo as a db
even for developing sqlite is good and you can change it fast whenever you want if you need to increase the size
yea sure , if you're good with dictionaries
Idk why there would be
Yeah and it's not too hard to shift from one SQL database to another
as long as there's an async wrapper I guess
!PyPi motor
its a private bot only
sqlite => asqlite would be good for you
simple setup etc
@slate swanyou can also use python instead of os.system ```py
filename = "home/bot/adx/channel"+str(guild.id)
if os.path.isfile(filename):
try:
os.remove(filename)
except PermissionError:
print("Missing permission to remove file")
You can make a dao abstract class that you can inherit to make daos for mongo, postgres, mocked data or whatever u want so you can always change it afterwards
It’ s still not the best way, but if It’ s ur preference no one is stopping u
I was using os.remove before but os.system is better
There is
There is even async odm
How can I add a rate limit
And orm
Wdym?
you probably just want cooldown on some commands
the docs of whatever lib you're using talk about decorators you can use on top of your command
alright
Ignoring exception in on_ready
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 154, in on_ready
await channel.send(embed=embed, delete_after=60)
File "/usr/local/lib/python3.8/dist-packages/discord/abc.py", line 1065, in send
data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
File "/usr/local/lib/python3.8/dist-packages/discord/http.py", line 248, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
is this bcs the bot doesn't have access to the channel?
Yep
is it possible to add aliases with ```py
@discord.ext.commands.cooldown()
Yes
ofcourse
at what position
It will still work the same except there will be a cooldown
is there a better way to do this
if str(channel.id) == file.read():
cuz this sends it only to couple discords for some reason
Whats file.read?
does command alias take a list and a tuple or just 1 of them?
@bot.command(aliases=["alias","es"])
@discord.ext.commands.cooldown(...
async def command(....```
@discord.ext.commands.cooldown(rate = 1, per = 2.0, aliases = ["who is", "Who is", "who's", "Who's"])
```so like will this work?
oh
List
alright thanks
No u keep everything the same except u add another decorator
if I have passed smth like aliases=("test", "smth") it would be wrong?
thanks
im wondering rn how can you give a command alias a spaced alias like 'this for example'
Do you have a fike for every channel?
yes
anyone have an idea how you can do this
Only with command groups
and all of them include a channel id
wdym
Attach debugger and see what file.read() returns
You need to create a command group
But It’ s not practical for 1 cmd
what's a cmd group again i forgot 😓
!d discord.ext.commands.Group
class discord.ext.commands.Group(*args, **kwargs)```
A class that implements a grouping protocol for commands to be executed as subcommands.
This class is a subclass of [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") and thus all options valid in [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") are valid in here as well.
Thx
ohhhh, that shit ive never heard of
It's really useful
example?
It’ s not practical for only 1 cmd
Read the docs
its gonna return ids
which is gonna be pain to check them all
ok
As a list?
no
As one string?
no
not in the same file
seperate files, the file.read was in a loop
921875157688152074
921875157688152074
921875157688152074
921875157688152074
921425507998900245
921425507998900245
921425507998900245
921425507998900245
921425507998900245
920742277809332295
920742277809332295
920742277809332295
920742277809332295
920742277809332295
920742277809332295
920742277809332295
920742277809332295
920742277809332295
920742277809332295
920742277809332295
920742277809332295
920742277809332295
920742277809332295
920742277809332295
920742277809332295
920742277809332295
920742277809332295
920742277809332295
920742277809332295
920742277809332295
920742277809332295
920742277809332295
914927659992117271
914927659992117271
914927659992117271
914927659992117271
sorry flood
Dw
but it returns shit ton of ids
why are all the channel ids the same
So what is this returned by
hm
no idea
Send ss of the code
!past
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.
do u also want where it writes the ids or only the loop where it checks them?
All
you're making a help command with the bad bot.remove_command and making a custom help command using async def help....
Now you would need help for commands too right? Like !help ping etc , you get to ways here
1 py async def help(ctx , command = None): if command == "ping": #do something to send ping help
With groups you can do it easier ```py
@bot.group()
async def help(ctx)
......
@help.command()
async def ping(ctx):
send help for ping```
oh
Why do you store data in separate files
easier
i wonder what you would pass in on @bot.group() tho
No it complicates everything
i mean below the asynchronous function of defining the bot group ofc
Pass
tru
or your main help command
Or some functionality that It’ s common for all of them
yeah
invoke_without_command exists too
So if you just use . command it does something
Yes u can use it as It’ s own command as well
darnit thought that existed
*didn't ig
does ctx.invoked_command even exist :(
@cedar stream u got any idea why the code is brokeN+
Nah
invoked_subcommand exists tho
For starters, you have a file for each channel with It’ s id and u read it from there
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.
Send code
doesn't matter cuz it worked before like that
Id consider using db tho
nah
@bot.group()
async def Read(ctx):
pass
@Read.command()
async def logs(ctx):
with open('log.txt', 'r') as log:
text = ""
for log in logs:
text += f"\n{log}"
await ctx.send(f"```\n{text}```")
oh it glitched because i was doing the 3 backticks
no my discord code text
Make the function name snake_case
Not PascalCase
Btw you can use logging library for logs and store them in .log file
u talking to me?
Yea
wtf dis shit
this the big error
Yes
would this work
with open("channel"+str(message.guild.id), "r") as file:
if len(file.read() <= 5):
os.system("rm -r home/bot/adx/channel"+str(message.guild.id))
else:
with open("channels", "a") as file:
file.write(file.read())
nvm i got it wrong, the command is named logs
Run it and see if it works
@shadow wraith
logs is your command name.lol @shadow wraith
i alr noticed that 💀
That is PascalCase
If you really want the command to have its first letter capital , just use the name kwarg
This is camelCase
Yea
Or make the bot case insensitive
Thanks for correcting me
👍
if os.path.exists("home/bot/adx/channel"+str(guild.id)):
with open("channel"+str(guild.id), "r") as file:
tf = file.read()
if len(tf <= 5):
os.system("rm -r home/bot/adx/channel"+str(guild.id))
else:
with open("channels", "r") as file:
if tf not in file.read():
with open("channels", "a") as file:
file.write(tf+"\n")
why aint this working
ah nvrm
what is it supposed to have in the file?
its a channel id in the file
and im checking if the channel id has less than 5 numbers its invalid
which works
but the else:
len(tf <= 5) should't it be len(tf) <= 5:
and stuff after that doesn't
can command groups have aliases?
typo probably
yes
all commands can have alias, juse add aliases=[]
@commands.group(name="dj", invoke_without_command=True)
async def dejay(self, ctx)
...
@dejay.command(name="quit", aliases=["q"])
async def quit_subcommand(self, ctx):
``` like this
@shadow wraith yeah that should do it
still not working
any errors?
no
no can bot groups itself have like aliases like for example a bot group is named 2 things, This and That, how would you name it 2 things at once
@shadow wraithjust try add that aliases=[""] and see
if it works it works, if not it dosnt 😛
it works
i dont use a computer, i use laptop ☠️
it is still a computer aint it?
lmao how does that matter
it dosnt 😄
it wont explode afterall
kek
yeah, it'll defuse
Traceback (most recent call last):
File "/home/container/.local/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/container/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 855, in invoke
await self.prepare(ctx)
File "/home/container/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 789, in prepare
await self._parse_arguments(ctx)
File "/home/container/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 697, in _parse_arguments
transformed = await self.transform(ctx, param)
File "/home/container/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 542, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: info is a required argument that is missing.```
read the error bruh
add ,error
in args
but i still i dont errors brush
even if i read the error
info is a required argument that is missing.
i got this when i using +statinfo command
info argument is missing
but what i need to do to get work
oh
async def statyinfo(ctx, info):
server = ctx.guild
if info == "memberCount":
await ctx.send(server.member_count)
elif info == "numberOfChannel":
await ctx.send(len(server.voice_channels) + len(server.text_channels))
elif info == "name":
await ctx.send(server.name)
else:
await ctx.send("Dziwne... tego nie wiem")```
yeah
i got like this
now your command <parafix>statyinfo memberCount
but where to i need to add this
oh
his prefix is + im sure
do +statyinfo memberCount ez
anyway your error was only that missing argument info
thx
np
yes
why does this return false ```py
if os.path.exists("home/bot/adx/channel"+str(message.guild.id)):
even tho the file exists
On message errror
Add
file extension?
nope
doesn't have
its literally just channel+id
wdym , you have files named 12345566667754 ?
huh
yes its channel+guildid
the name
without any extensions like .txt or something? , weird
no
no reason to have .txt
doesn't do anything
i have a question how i can make command that shows channles count and roles count
!d discord.Guild.roles
property roles: List[discord.role.Role]```
Returns a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of the guild’s roles in hierarchy order.
The first element of this list will be the lowest role in the hierarchy.
!d discord.Guild.channels
property channels: List[GuildChannel]```
A list of channels that belongs to this guild.
use len() on these
ok
fuck
im dumb
whats the opposite of append
like remove 1 line from code
pop
list?
file*
with open("channels", "pop") as file:?
await ctx.send(len(server.roles)) it could work or its wrong cuz i just wonna add thing in my command thats counts all roles the server but idk its good or not
or p or what
just open as read ("r") and then delete the line you want
?
bruh what
u cant delete with read
as "w"
pls can sameone checks and tells its good or its no made properly
no, it's guild.roles not server.roles
oh ok
with open ("filename.txt", "r") as f:
lines = f.readlines()
with open("filename.txt", "w") as f:
for line in lines:
if line.strip("\n") != "line you want to delete":
f.write(line)
should do the trick - gets the file by opening it in read, opens in w and overwrites the file with everything except the line you want to delete
await ctx.send(len(guild.roles)) it should look like this?
to get channel I did await self.bot.get_channel(id), right?
or not
sure if u have defined guild
and if I have a message obj, can I reply to that message using .reply?
oh
no
you dont await get_
i need to check what mz but do when i type +rolesCount
you await fetch_
oh..
fetch calls api, get searches cache
ooh
What you have is right, but before that you should have guild = ctx.guild
Also worth noting that everyone (defualt role) is counted as a role so you'd ideally want len(guild.roles)-1
my python3 file keeps getting killed for no reason
just says "Killed"
and quits
no errors
ok but where do i add it
1 python bot cant be using 4gb ram
guild = ctx.guild
await ctx.send(len(guild.roles)-1)
just killed not killed (program exited with code X) ?
yikes
could you run it on your own machine and monitor ram usage?
sure
https://github.com/Rapptz/discord.py/issues/5824 the exact same issue here says it's RAM problem and that's all I can think of too
i said not a
I host my bot on a vds
but oliver asked me to try it on my own
yes
@slate swanbut yo thats 100% cpu of python3 seems scary
100% of a thread
async def statyinfo(ctx, info):
server = ctx.guild
if info == "memberCount":
await ctx.send(server.member_count)
elif info == "numberOfChannel":
await ctx.send(len(server.voice_channels) + len(server.text_channels))
elif info == "name":
await ctx.send(server.roles_count)
guild = ctx.guild
elif info == "rolesCount":
await ctx.send(len(guild.roles)-1)
else:
await ctx.send("Dziwne... tego nie wiem")``` like this
class HelpView(View):
message : Message
def __init__(self ):
super().__init__(
timeout=5
)
async def on_timeout(self):
self.children[0].disabled = True
await self.message.edit(
content= '`Menu Options` is no longer active',
view=self
)
class InviteButton(Button):
def __init__(self , ctx : Context):
super().__init__(
emoji= "🔗",
label = 'Invite',
url = ctx.bot.invite_url,
style = ButtonStyle.url
)
class VoteButton(Button):
def __init__(self , ctx : Context):
super().__init__(
emoji= ctx.bot.get_emoji(841178289171333120),
label = 'Vote',
disabled=True,
url = f"https://top.gg/bot"+str(ctx.bot.user.id),
style = ButtonStyle.url
)```
why does this show an error saying
`In components.0.components.1: The specified component exceeds the maximum width`
`In components.0.components.2: The specified component exceeds the maximum width`
when the timeout is set to 60 , but not when at timeout =4 or some small number
and my laptop has 16 threads
aaah - i should have checked CPU overall
since u have already defined server, do server.roles instead
Why ur discord look like that
betterdiscord
@slate swanmaybe not leak ur serverip, and why run as root? :S
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
u can literally get my server ip from my about me
my website running on the same ipv4
guild = ctx.guild
^
IndentationError: unindent does not match any outer indentation level``` i got this when run my bot
it means you havnt correct indentation
so what i should do
bro aint nobody gonna bruteforce my 32 char "#=¤_abcABC password
ok but i would recommend no root allowed and setup privatekeys
nahh
@slate swanhave u figured it out yet?
@bot.command()
async def statyinfo(ctx, info):
server = ctx.guild
if info == "memberCount":
await ctx.send(server.member_count)
elif info == "numberOfChannel":
await ctx.send(len(server.voice_channels) + len(server.text_channels))
elif info == "name":
await ctx.send(server.roles_count)
guild = ctx.guild # hint: problem is here
elif info == "rolesCount":
await ctx.send(len(guild.roles)-1)
else:
await ctx.send("Dziwne... tego nie wiem")
but it makes no sense what u trying to do there
@bot.command()
async def statyinfo(ctx, info):
server = ctx.guild
if info == "memberCount":
await ctx.send(server.member_count)
elif info == "numberOfChannel":
await ctx.send(len(server.voice_channels) + len(server.text_channels))
elif info == "name":
await ctx.send(server.roles_count)
guild = ctx.guild #remove this
elif info == "rolesCount":
await ctx.send(len(guild.roles)-1) # edit this to len(server.roles)-1
else:
await ctx.send("Dziwne... tego nie wiem")
ok
fuck
i hate this gdamn python
how
in the fuck do I get a list of all channels in the guild
!d discord.Guild.channels
property channels: List[GuildChannel]```
A list of channels that belongs to this guild.
bro
wtf is wrong with my code
@bot.command()
async def start(ctx):
if ctx.author.guild_permissions.manage_channels:
if ctx.channel.is_nsfw() == False:
embed = discord.Embed(description="Turn on NSFW mode!", color=0xFFFF)
await ctx.send(content=None, embed=embed)
else:
with open("channels", "r") as file:
text_channel_list = []
for channel in ctx.guild.text_channels:
text_channel_list.append(channel)
if os.path.exists("/home/bot/adx/autoporn"+str(ctx.guild.id)) == False and str(text_channel_list) not in file.read():
autoporn = True
embed = discord.Embed(title="> __A-NSFW__", description="Started auto-nsfw. Use a!stop to stop.", color=0xFF000)
embed.add_field(name="Estimated time before start", value="1-10min", inline=False)
await ctx.send(embed=embed)
file = open("autoporn"+str(ctx.guild.id), "w")
file.write("enabled")
file.close()
file = open("channels", "a")
file.write(str(ctx.channel.id)+"\n")
print("debug99")
file.close()
break
else:
embed = discord.Embed(title="> __A-NSFW__", description="Auto-NSFW is already running.", color=0xFF0000)
await ctx.send(embed=embed)
break
else:
embed = discord.Embed(title="> Missing permissions!", description="manage_channels", color=0xFF0000)
await ctx.send(embed=embed)
all commands stop working after doing a!start
oi you didn't write the extensions in filenames
not needed
Hmm
This code is a bit blocking
You should use an asynchronous dB like aiosqlite or asyncpg or motor
no
also nothing should be blocking
cuz it has break at the end
it should just break out of the loop as soon as its done
what is the replacement for avatar_url for disnake?
cant be the problem cuz this works
@bot.command()
async def stop(ctx):
if ctx.author.guild_permissions.manage_channels:
text_channel_list = []
for channel in ctx.guild.text_channels:
text_channel_list.append(channel)
with open("channels", "r") as file:
print("debug5")
if os.path.exists("/home/bot/adx/autoporn"+str(ctx.guild.id)) == True or os.path.exists("/home/bot/adx/channel"+str(ctx.guild.id)) == True or str(text_channel_list) in file.read():
file.close()
print("debug1")
os.system("rm -r /home/bot/adx/autoporn"+str(ctx.guild.id))
os.system("rm -r /home/bot/adx/channel"+str(ctx.guild.id))
g = str(text_channel_list)
with open ("channels", "r") as f:
lines = f.readlines()
with open("channels", "w") as f:
for line in lines:
if line.strip("\n") != str(g):
f.write(line)
print("debug3")
autoporn = False
embed = discord.Embed(title="> __A-NSFW__", description="Stopped auto-nsfw. Use a!start to start again.", color=0xFF000)
await ctx.send(embed=embed)
break
else:
embed = discord.Embed(title="> __A-NSFW__", description="Auto-NSFW isn't running on any channel.", color=0xFF0000)
await ctx.send(embed=embed)
break
else:
embed = discord.Embed(title="> Missing permissions!", description="manage_channels", color=0xFF0000)
await ctx.send(embed=embed)
Its avatar.url in both disnake and discord.py v2.0
okay thanks
anyone?
?
Can you ss the whole code
Erm, what do you mean?
command.get_commands returns a list of command objects right?
who's code is this?
Yeah.
how do i fix category appearing 2 times in help command? im using HelpCommand btw
Try using [cmd.name for cmd in command.get _commands()] to get list of command names as string
Show code
Alright
async def send_bot_help(self, mapping):
ctx = self.context
em = discord.Embed(
title=f"{ctx.me.display_name} Help Menu",
timestamp=ctx.message.created_at,
color=bot.christmas
)
em.set_thumbnail(url=ctx.me.avatar_url)
usable = 0
for cog, commands in mapping.items():
if filtered_commands := await self.filter_commands(commands):
amt_cmds = len(filtered_commands)
usable += amt_cmds
if cog:
name = cog.qualified_name
description = cog.description or "No description"
else:
pass
em.add_field(name=f"{name} [{amt_cmds}]", value=description, inline=False)
em.description = f"""{len(ctx.bot.commands)} commands | {usable} usable\n\nUse "help [command | module]" for more info.\nIf you can't see any module, it means that you don't have the permission to view them.\n\n`<>` required | `[]` optional"""
await self.send(embed=em)
Can u put it in pastebin or send ss
Cus I’ m on mobile
Ok
!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.
hello i want to make the bot automatically assign a role to member when i type a command with the mentioned member
he prob took it from internet
Ah, it works
I hope he didn't came up with it himself
Does every cog get shown twice
Nice
Thank you.
Np
impossible he dont even know intendations 😛
listing its aliases is also interesting
@commands.has_any_role(921080099061784646,921080899209142282,921089622979788800,921078007668568064,921079589860696074,920779847305932827)
async def CIA(ctx, *, text):
try:
await ctx.message.delete()
timenow = time.strftime("%H:%M")
content = value=text
channel = client.get_channel(920779848073502816)
embed=discord.Embed(title="CIA REDIRECTION", description=" ", color=0xfff705)
embed.set_author(name="CIA", url="", icon_url="https://cdn.discordapp.com/icons/920779847012319233/1d540f5fed2274526dc69322ad56b312.png?size=4096")
embed.set_thumbnail(url="https://cdn.discordapp.com/icons/920779847012319233/1d540f5fed2274526dc69322ad56b312.png?size=4096")
embed.add_field(name="برجاء التوجة لروم الامن الوطني للتحقيق", value=text, inline=False)
embed.set_image(url="https://cdn.discordapp.com/attachments/920779848073502816/922594384535506985/CIA2.gif")
embed.set_footer(text=f"{CIA} {timenow}")
test = await channel.send(embed=embed, content=content) # Define the messag
except Exception as err:
print(err) ``` don't mind arabic words because i'm arabic
so all the things i want it to do is to automatically add a role to the mentioned user
nope just one
!d discord.Member.add_roles()
No documentation found for the requested symbol.
what is !d?
Can u paste whole class
For docs
and which line
@slate swanwhats the error?
there is no error
!d discord.Member
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
hash(x) Returns the member’s hash.
str(x) Returns the member’s name with the discriminator.
well, you should just have a member: discord.Member parameter, that way, you can just call
await member.add_roles(...)
i want it to add a role to the mentioned member in the embed
content = value=text this looks weird tho
well discord.Member is the member i mentioned right?
that's just basically
content = text
value = text
how do I id of ctx.guild.text_channels
i think it's just discord.Member.add_roles
does member.add_roles accept role id?
oh ok still looks weird 😄
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
i mean he could just do below instead of -> test = await channel.send(embed=embed, content=content) py test = await channel.send(embed=embed, content=text)
via list comprehension
text_channel.id on every elem
true, there's many more wrong with that code, but yeah
i dont want a for loop
don't underestimate them
it'll go fast af, you won't notice, it's not like you're doing this for millions of elements and need numpy xd
Print out mapping and send me the output
that's english
local variable 'member' referenced before assignment
the problem id I had a for loop before on it and it was broken
nah, probably the way you wrote it, for loops aren't that bad
that means you try use member variable but its not declerade yet
that's a basic python error, obviously your first project
how do i declerade it
sorry i'm just new so i may ask some bad questions
well, what should the member be? the command invoker?
no a mentioned user
maybe show code
it didnt print anything
like when i do *CIA @slate swan
well, is he mentioned while invoking the command?
of your comand function decleration
well, you need to add that parameter to you function ofc
Did u run the command?
like ctx, member: discord.member)
async def CIA(ctx, member: discord.Member, *, text)
You gotta put in role object
so then?
wtf is wrong with my code
@bot.command()
async def start(ctx):
if ctx.author.guild_permissions.manage_channels:
if ctx.channel.is_nsfw() == False:
embed = discord.Embed(description="Turn on NSFW mode!", color=0xFFFF)
await ctx.send(content=None, embed=embed)
else:
with open("channels", "r") as file:
text_channel_list = []
for channel in ctx.guild.text_channels:
text_channel_list.append(channel)
if os.path.exists("/home/bot/adx/autoporn"+str(ctx.guild.id)) == False and str(text_channel_list) not in file.read():
autoporn = True
embed = discord.Embed(title="> __A-NSFW__", description="Started auto-nsfw. Use a!stop to stop.", color=0xFF000)
embed.add_field(name="Estimated time before start", value="1-10min", inline=False)
await ctx.send(embed=embed)
file = open("autoporn"+str(ctx.guild.id), "w")
file.write("enabled")
file.close()
file = open("channels", "a")
file.write(str(ctx.channel.id)+"\n")
print("debug99")
file.close()
break
else:
embed = discord.Embed(title="> __A-NSFW__", description="Auto-NSFW is already running.", color=0xFF0000)
await ctx.send(embed=embed)
break
else:
embed = discord.Embed(title="> Missing permissions!", description="manage_channels", color=0xFF0000)
await ctx.send(embed=embed)
all commands stop working after doing a!start
does this accept role id?
does it send anything?
no
I believe it only accepts role object
wdym?
nothing works after doing a!start
i forgot lol, but when i did, it printed some large things
docs will tell you
but the debug99 prints so the whole code works,
so wtf
I think if you have on_message event in main file, the other commands wont work
docs link?
just follow your code... and you'll find the error
what is role object ;-;
what bruh
why wouldn't it
Put it in pastebin
and yes I do have on_message
!d discord.Role
class discord.Role```
Represents a Discord role in a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild")...
because on_message is greedy, it'll "take" the functions away of other commands
Idk, ik I used to have problems with it but now I use cogs so I never paid attention
where do i put this
so for some reason this command that worked before, doesn't work anymore ?
await bot.process_commands(message)
i have
on_message gets triggered before a command, if you'd say in on_message has to shut down the bot, then it would should it down before running any other command
is that more clear?
yes
where do i put it
thats what happened when i added the async def @potent spear
that's english
Which cog does it display twice
I mean, that the error speaks for itself
cant be that cuz every command works before doing a!start and I have
await bot.process_commands(message)
Nowhere, you get it with the id
should the first if statement have == true after it? Like if ctx.author.guild_permissions.manage_channels==True?
print stuff in your if statements and check where the code gets in that command
how
basic python dude
well i'm not that good
it assumes its == True:
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
well, tell me what you copy pasted from me, tag me in the message
what
@potent spear this
makes no sense what u said lol
basic debugging mate
well, you obviously didn't add *, text after it
I have debug prints everywhere and even logger enabled
Attach a debugger and see what’s happening
if ...:
print("I got here")
else:
print("here")```
that way, you know your code actually runs till there etc
bro
ok, do you need additional info after adding *CIA @potent spear <extra text here>
yes or no?
nope
I have debug prints everywhere already
Poor debugger, getting replaced by print
i only want it to add the role to the mentioned user which is <@>
ah
File "main.py", line 210, in my_task
if os.path.exists("/home/bot/adx/channel"+str(msg.guild.id)):
is blocking the code
then remove the *, test
in your function declaration and also remove where you use it in the command
fucking fuc
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
Read this
show me
you can always test shit before implementing you know, just have a basic test command ready
@bot.command()
async def test(ctx):
# shit you want to test```
all of those are debugs so I know where the code is
and it literally just keeps going
almost every if statement has a debug
and the nsfw shit is from reddit
Use logging.debug for that
dont mind but anyways I have good debugging
So u can disable it w/o having to delete it
yea I'm using that also but I have it on warnings mode
Replace print statements with logging.debug and set level to debug and when you are finished debugging just set it back to info and leave logging.debug statements
how do i make button clickable more than once
2021-12-22 20:34:08,513:WARNING:discord.gateway: WebSocket in shard ID None is ratelimited, waiting 59.98 seconds
well well well
@cedar stream
Put embed.add field inside if statement
It already should be
!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.
A button only stops if you stop listening to a interaction
why doesn't this loop thru all channels
https://paste.pythondiscord.com/uratikipux.lua
only sends it on couple channels
Because u get ratelimited
cap
like?
Like @slate swan said
@mortal thistle
it says this interaction failed
Lemme see
why doesn't this loop thru all channels
https://paste.pythondiscord.com/uratikipux.lua
Dont think you can
ping?
Cus u get ratelimited
like the way Ticket Bot does
can we have multiple classes in one cog file?
Like, you cant send that many messages that fast
Yes why not
alr thanks
like this one
Ticket bot doesnt go offline too often, and it may replace old buttons with new ones when it restarts
but the message isn't edited
cant be
Does he edit the message to have new buttons?
it literally spams the same message on the same channel
and I have sleeps
Idk, mby he deleted the old msg, idk
Yes “it literally spams”
U can send 5 messages per 5 seconds I believe
Dont really know how does bots work
🤷🏼♂️
i know
what should I if? like if smth:
how do I do this sort of text format https://miro.medium.com/max/794/1*Xg6jwxRdt4htwC_pQWy5Wg.png
!d discord.Embed.add_field
add_field(*, name, value, inline=True)```
Adds a field to the embed object.
This function returns the class instance to allow for fluent-style chaining.
thanks
The existing if statement
so indent it once?
thanks, its fixed now! :D
Np
Those arent fields lol
Just a description
He just made new lines and made the titles bold
Its fine thats what I needed
await channel_one.send(...); await channel_two.send(...)
no
you do it as one would expect
no
I have a list of channel ids
I need to send msg to all of them
they are in different guilds
for channel_id in channel_list: #where channel_list is a list of id's
channel = bot.get_channel(channel_id) #searches bots cache for the channel
await channel.send(...)```
why not?
idk just didn't work before
future: <Task finished coro=<my_task() done, defined at main.py:216> exception=AttributeError("'NoneType' object has no attribute 'send'")>
Traceback (most recent call last):
File "main.py", line 268, in my_task
await channel.send(embed=embed)
AttributeError: 'NoneType' object has no attribute 'send'
invalid id.
not
can you show the list
['920751850649714738', '922978651803365417', '839546320820895747', '850592224700792872', '884962944482422784', '918770232485613568', '800069566519574536', '923135211003314206', '737324794852409358', '923205531852750948', '922898261507997726', '921875157688152074', '914927659992117271', '922133456102760520', '920742277809332295', '922133456102760520', '921425507998900245', '921496293002584074', '922771047760150568', '922771047760150568', '922865149105303622', '922864818191495191', '920751850649714738', '920742277809332295', '920751850649714738', '907915837049036850', '923283650911559711', '922771047760150568', '907915837049036850', '923290185783971913', '923290911016906852', '923295700484227076', '923295700484227076', '923295720147128370']

all those r channels
they have to be ints
bruh
for channel_id in channel_list: #where channel_list is a list of id's
channel = bot.get_channel(int(channel_id)) #searches bots cache for the channel
await channel.send(...)
channel_list = int(file.read()).split()
ValueError: invalid literal for int() with base 10: '920751850649714738\n922978651803365417\n839546320820895747\n850592224700792872\n884962944482422784\n918770232485613568\n800069566519574536\n923135211003314206\n737324794852409358\n923205531852750948
grool
nvm
you dont int a list...
yes
ik
I did it at the wrong variable
the for loop just chooses 1 random channel and keeps sending it there
then you've done the loop wrong
o
no
for channel_id in channel_list: #where channel_list is a list of id's
channel = bot.get_channel(int(channel_id)) #searches bots cache for the channel
file.close()
embed = discord.Embed(title="> __Channel inactive__", color=0xFF0000)
embed.add_field(name="Reason for inactivity", value="Restart by developer", inline=False)
embed.add_field(name="Note", value="Small bug fixes || Added new categories", inline=False)
await asyncio.sleep(3)
await channel.send(embed=embed)```
file.close()
Inefficient tho
whats that doing there? it looks fine other than that...
why did you put it in the loop though?
misplaced
are you sure you saved itr?
well you've fucked something up then :)