#discord-bots
1 messages · Page 951 of 1
i dont care lol
Then don't expect getting help here
whyy
Cz it's against ToS (:
LMAO
yeah that's cool, click it yourself
That's known as s p a m
i want to use some code for it
Its not spam.. it is just that i dont wanna share full info
Stop it, u won't get help here anyways 
why
because it's against discord tos
it is not
it literally is
How many times we gotta tell u dude
automating the api in any way is against terms of service
i dont have any issues with bot token
Using a user token in anything is against ToS
<@&831776746206265384>
We have told u multiple times but u dont want to hear it, so Mods will tell u themselves in their way 🤷♂️
@slate swan helped me with the code but there is a new error
" File "/Users/alanabeaton/Avery Bot/main.py", line 25, in <module>
bot = MyBot(command_prefix='avery ', case_insensitive=True, help_command=None)
File "/Users/alanabeaton/Avery Bot/main.py", line 10, in init
super().init(*args, *kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 167, in init
self.__tree: app_commands.CommandTree[Self] = tree_cls(self) # type: ignore
TypeError: 'str' object is not callable"
In short, stop asking for help related to user tokens
bot tokens
from curses.panel import bottom_panel
from distutils import command
import discord
import os
from discord.ext import commands,tasks
from discord.ext.commands import has_permissions, CheckFailure
class MyBot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, *kwargs)
async def setup_hook(self):
for ext in ['cogs.ModerationCog', 'cogs.CommandEvents', 'cogs.HelpCommandCog', 'cogs.UtilitiesCog', 'cogs.FunCog']:
await self.load_extension(ext)
async def on_command_error(self, ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send('**Please type in the full command ** ')
if isinstance(error, commands.MissingPermissions):
await ctx.send("**You dont have all the requirements necessary to run this command :angry:**")
def run(self):
super().run("Your token!")
bot = MyBot(command_prefix='avery ', case_insensitive=True, help_command=None)```
@lone hare please don't ask for help with botting user accounts, that breaks discord's TOS
okay, i don't have any issue in using BOT token
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
That's all?
?
^ this is the error and yes thats the code
Weird, I don't see any issue
weird error tbh it seems like it was raised internally
Well many times the traceback isn't printed completely and it's our code error, not internals but idk in this case 🤷♂️
do you have the full traceback

Stop with yr weird emojis
/usr/local/bin/python3 "/Users/alanabeaton/Avery Bot/main.py"
alanabeaton@sonic lintels-Air Avery Bot % /usr/local/bin/python3 "/Users/alanabeaton/Avery Bot/main.py"
Traceback (most recent call last):
File "/Users/alanabeaton/Avery Bot/main.py", line 25, in <module>
bot = MyBot(command_prefix='avery ', case_insensitive=True, help_command=None)
File "/Users/alanabeaton/Avery Bot/main.py", line 10, in init
super().init(*args, *kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 167, in init
self.__tree: app_commands.CommandTree[Self] = tree_cls(self) # type: ignore
TypeError: 'str' object is not callable
Also, remove the init method since u ain't really doing anything in it
but she is?
shes passing all the arguments lol
no
it's literally just calling the parent init
with the arguments getting passed?
when I removed it this was the error
/usr/local/bin/python3 "/Users/alanabeaton/Avery Bot/main.py"
alanabeaton@sonic lintels-Air Avery Bot % /usr/local/bin/python3 "/Users/alanabeaton/Avery Bot/main.py"
Traceback (most recent call last):
File "/Users/alanabeaton/Avery Bot/main.py", line 24, in <module>
bot.run('token removed')
TypeError: run() takes 1 positional argument but 2 were given
can you try this?
ok
how are you passing the token
in the subclass i only added one param
and how are you calling the eventual run
the overwritting run method doesnt 2 positional arguments only self
by just directly putting in the token
bot.run('thebotstoken')
you needed to pass the token in the method of the subclass lol
That's not how you install the master branch....
yes you just downgraded versions

But it should be not since the default value is a CommandTree unless it's overrided
https://github.com/Rapptz/discord.py/blob/18050aecd7c2718634a2dd4336e667a899da0859/discord/ext/commands/bot.py#L159
discord/ext/commands/bot.py line 159
tree_cls: Type[app_commands.CommandTree[Any]] = app_commands.CommandTree,```
^
and I don't see them doing that in their code
pip install git+https://github.com/Rapptz/discord.py
👌
still the same error
Yea
What's the error?
Just do bot.run() now, don't do bot.run(token)
can someone pls help me?
/usr/local/bin/python3 "/Users/alanabeaton/Avery Bot/main.py"
alanabeaton@sonic lintels-Air Avery Bot % /usr/local/bin/python3 "/Users/alanabeaton/Avery Bot/main.py"
Traceback (most recent call last):
File "/Users/alanabeaton/Avery Bot/main.py", line 25, in <module>
bot = MyBot(command_prefix='avery ', case_insensitive=True, help_command=None)
File "/Users/alanabeaton/Avery Bot/main.py", line 10, in init
super().init(*args, *kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 167, in init
self.__tree: app_commands.CommandTree[Self] = tree_cls(self) # type: ignore
TypeError: 'str' object is not callable
i would check src on how the error was raised but i turned off my pc
from curses.panel import bottom_panel
from distutils import command
import discord
import os
from discord.ext import commands,tasks
from discord.ext.commands import has_permissions, CheckFailure
class MyBot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, *kwargs)
async def setup_hook(self):
for ext in ['cogs.ModerationCog', 'cogs.CommandEvents', 'cogs.HelpCommandCog', 'cogs.UtilitiesCog', 'cogs.FunCog']:
await self.load_extension(ext)
async def on_command_error(self, ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send('**Please type in the full command ** ')
if isinstance(error, commands.MissingPermissions):
await ctx.send("**You dont have all the requirements necessary to run this command :angry:**")
def run(self):
super().run("my bots token")
bot = MyBot(command_prefix='avery ', case_insensitive=True, help_command=None)
bot.run()```
no
Prolly a bug

I need helps in cogs i connected it btw still noy getting any response from it how to solve this
what you want
half fixed rewrote to disnake because d.py is being so annoying
Huh?
@cool.command(name='unban')
async def unban(ctx, *, member):
banned_users - await ctx.guild.bans()
member_name, member_discrimnator - member.split('#')
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
await ctx.send(f"Unbanned {user}")
return
NameError: name 'banned_users' is not defined
Hey i am having cogs prob pls help
Code
I smell Lucas Unban 👀
what
U copied that from Lucas?
no
Then
web

i prob couldve made myself but i was too lazy lol
ok
it stinks 
you did - instead of =
in the definition of banned_users
I hav loaded cogs btw it is not working. Why?
show code
Its too long lawl w8
!pastebin
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.
I'm trying to set up slash commands, but nothing was showing up. So to make sure I wasn't doing anything wrong, I tried the template:
@tree.command(guild=discord.Object(id=507364684924452896))
async def slash(interaction: discord.Interaction, number: int, string: str):
await interaction.response.send_message(f'{number=} {string=}', ephemeral=True)
But nothing is showing up. No errors, no nothing
H
Sad
Can I Make this User Banned But Message not sent
send the message before banning the user

imagine the ban fails
Im having an issue with cogs with disnake. The cogs don't seem to be loading at all or something because I'm getting no messages in the terminal at all and its just not working.
show the loading part
from curses.panel import bottom_panel
from distutils import command
import disnake
import os
from disnake.ext import commands,tasks
from disnake.ext.commands import has_permissions, CheckFailure
bot = commands.Bot(command_prefix='avery ', case_insensitive=True, help_command=None)
bot.remove_command('help')
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send('**Please type in the full command ** ')
if isinstance(error, commands.MissingPermissions):
await ctx.send("**You dont have all the requirements necessary to run this command :angry:**")
extensions = ['cogs.ModerationCog', 'cogs.CommandEvents', 'cogs.HelpCommandCog', 'cogs.UtilitiesCog', 'cogs.FunCog']
if __name__ == '__main__':
for ext in extensions:
bot.load_extension(ext)
bot.run('')```
is there any way to make unbanall comand
Just doesn't do anything
yes
? how
@sonic lintel was that issue fixed?
How to fix
u forgot to await something
await bot.add_cog
^
Ok ok
nvmd
?
@slate swan cant await @maiden fable out side
In dpy 2.0 all the extensions loading and cog adding were made async
Make your setup functions async as well
Not sure how to load extensions without subclassing the bot now
3 improvements for your code
-
You don't need to call
bot.remove_command("help")after you set it toNonein the constructor -
For error handler
elifexists, a bunch of ifs just greatly slows it down -
Disnake has a useful tool called
load_extensionswhich loads all the extensions in the folder
And yeah forth
Add this to your error handler
else:
raise error```
That's why you aren't getting any errors
!d
I got a ghost ping
Iterate through discord.Guild.bans using async for and unban them by doing await guild.unban(discord.Object(id=...)) ```py
async for entry in guild.bans():
...
stop pinging them
Using disnake
Sorry
are you using disnake and d.py together?
show me the cog
why're you awaiting load_extension then?
doesn't only d.py do that
show me the start of the class
Ok antinuke?
yes?
show your imports
you don't need to ping me everytime
No replit doesnt identify discord.ui module as discord is of 1.7.3 version and if i install dpy v2 also after sometimes idk why replit dels all the imported packaged its replit problem and then again i have to manually install dpy v2
I cant run the bot till i installed dpy v2 for 10 mins
@boreal ravine cant i import cogs from disnake?
yeah because replit uses an ephemeral file system
wdym 'import'
Load*
yes
is there a way i can use with open and open 2 files (not at once) then read both and do an if statement like this:
if ctx.author.id not in first_file and second_file:
just don't use replit, it's shit for hosting discord bots
yes, but its if ctx.author.id not in first_file and ctx.author.id not in second_file:
ok thanks
How to solve this error of cogs wuth disnake
Hi, I'm making a discord bot and I need a way to edit a text channel so that only a specific user will be able to see it. I would give the user a role which can access the channel, but I need it such that other users are unable to tell which channel every user has access to
do u happen to know how i can count for str(ctx.author) in this example:
with open("test.txt", "r") as a:
if str(ctx.author) more than 5 times in a.read():
obviously the second line is wrong, but what are the correct words for it? and what would i have to add
if str(a.read()).count(str(ctx.author)) > 5:
...
counts how many times the author is in the file
yes
why so?
i think it returns a string though so no need to cast
unsure
alright ill try this
how do i open 2 text files with 1 line but the text files both have a different variable
idk if variable is the correct word for it
with open("file1.txt", "r") as a, with open("file2.txt", "r") as b:
something like this? maybe
tias, but ```py
file1, file2 = open(PATH), open(PATH)
that still uses with open() right?
no
then specify them, open(PATH, "r")
alright
so if im correct, this code would open test1.txt under the name of file1 and would open test2.txt under the name of file2?
file1, file2 = open("test1.txt", "r"), open("test2.txt", "a")
yes
ok thx
👍
what does tias mean
try it and see
for some reason, to run the command the User needs to have permissions
shouldn't it be the person who executes the command?
the command author needs the permission to run the command
the author of the command needs to have the permissions, and if im understanding you correctly thats what you are saying
but, well if your bot doesnt even have the permissions to give a role then it wont work
so it didnt work
yea but it was because i was trying to add a role above me
lmfao
i tested it out, and changed it to 4: but it lets there be 5, only then it doesnt allow me to
and if i do 5: then it lets there be 6 until it doesnt allow me to
whats 4:
if str(a.read()).count(str(ctx.author)) > 4:
use >=, it checks if x is bigger or equal to y
alright, ima try that
it worked, tysm
honestly youre probably the person that has helped me the most here everyone else started telling me to use json, databases and dictionaries and other stuff
You can do ```py
with open("file1.txt", "r") as a, open("file2.txt", "r") as b:
...
yeah, i used that it worked fine for me
is it possible to make every command on a bot use slash commands? pretty much every command on ur bot has a slash command to it to
Just add different decorators
Context and Interaction share most of their attributes besides some so I'd suggest creating separate commands instead of doing multiple decorators on a single function
ty
question is it possible to make a command that transfers to different channel? Like a suggestion command where when u suggest something it sends to a channel
Just take the message and store it into a variable
Then send it to another channel
What is the defination of async function
app = FastAPI()
bot = discord.Client()
bot = commands.Bot(command_prefix='!')
@app.on_event("startup")
async def startup_event():
asyncio.create_task(bot.start(discordTOKEN))
await asyncio.sleep(4)
print(f"{bot.user} has connected to Discord!")
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
bot.load_extension(f'cogs.{filename[:-3]}')
@app.get("/")
async def hello():
return "Welcome to Pikachu Pricer. Made by @Johnny Black#6363"``` anyone here knows why !ping doesnt work here?
is there another way to make a slash command only visible to you other then ephemeral=true
async def ping(self, ctx: commands.Context):
print("Checking the bot's current websocket latency.")
embed=discord.Embed(title=":ping_pong: Pong! :ping_pong:", description=f"{round(self.bot.latency * 1000)}ms", colour=000000)
await ctx.message.delete()
await ctx.send(embed=embed)
print("Sent the bot's current websocket latency.")```
is there another way to make a slash command only visible to you other then ephemeral=true
Nope
breh i used one before, i just forgot what it was
What's the issue?
I cant use !ping
Why? Can you elaborate
nvm i found it it was hidden=True
idk it seems like something is blocking the bot from receiving commands
Do you have an on_message event?
hmm nope I showed my discord code above
Is that all your code?
yep
You don't have the @bot.command() decorater
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.command()
@commands.cooldown(rate=1, per=3)
async def ping(self, ctx: commands.Context):
print("Checking the bot's current websocket latency.")
embed=discord.Embed(title=":ping_pong: Pong! :ping_pong:", description=f"{round(self.bot.latency * 1000)}ms", colour=000000)
await ctx.message.delete()
await ctx.send(embed=embed)
print("Sent the bot's current websocket latency.")
``` u mean this?
nvm Im gonna split them into 2 program
much easier
and the cooldown decorator should be @commands.cooldown(1, 3, commands.BucketType.member)
alright thanks dude
did it work?
client.get_guild(953173697886302268)
print(guild.members)
``` this returns
[<Member id=853195733205123072 name='Monkeu' discriminator='1696' bot=False nick=None guild=<Guild id=953173697886302268 name='Legit Rewards' shard_id=None chunked=False member_count=437>>]
i want to get members
member what? member names?
for member in guild.members
if member.name == "something":
members.send("hi")
something like that
don't push them away please
that's correct. just await the member.send("hi")
I force him to work with docs
this is one of the most important developer skill
isn't it mate?
You can at least redirect him to the proper docs using the !docs command.
Secondly, bot.get_guild exists.
!d discord.ext.commands.Bot.get_guild
get_guild(id, /)```
Returns a guild with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
I think he have to check it by himself
isn't this channel consider to show the right way to fix your problem and not do whole code for someone
I think people should find the right way by many attempts
Yup, smart way is ask someone how faced with this problem
but its discord py
its like a lego bricks
Nobody asked for the whole code, though, and nobody also noticed that this is probably a member intents issue
Also, like, the “whole code” is small enough because their question is small, so I wouldn’t say it’s inappropriate if they wanted it
alright thanks
you do know that this channel is here for people who are new to discord bots. And the PURPOSE of this channel is to help them with simple examples and direct them towards the right docs if they fail to do so
Ashley
Raven
Do you know how I can take a screenshot of messages with a bot
Wait what
I dont think you can
yes, you cant
thats horrible first of all
lmao
well, no my intention isn't bad its just for testing
I've seen a bot with a google command that shows an image of the search result
so wanted to see if I can replicate it
ah well it may be fine for testing, but it isnt possible because the bot doesnt work on a UI
Which bot
could you show?
🗿
pfftt lemme check out
You probably should of
I mean the sniping possibilities are still possible
Using pillow
@spring flax what you could do is, host the bot on a computer of yours and use os or webbrowser module to query with your preferred search engine, take a snip of the page using PIL and close the webpage and save the image and send the image via your bot
found it
^^
you have to press the button
channel = bot.get_channel(channelid)
in this case, if channelid a str or int?
A int
ok
search("query")
snippet = Snip((location))
snippet.save("test.png")
close("web browser")
send(file="test.png")
@spring flax this is what you will have to do
okay nevermind then
@discord.ui.button(label='Quit', style=ButtonStyle.red)
async def quit(self, interaction: discord.Interaction, button: Button):
"""
Go back to `select-view`
Needs to be implemented in a subclass.
"""
pass
i got that in the parent class, im trying to overwrite and interact with that button
async def quit(self, interaction: discord.Interaction, button: discord.Button):
""" Go back to `select-view` """
await interaction.response.edit_message(embed=self.cls.wiki['about'], view=self.cls)
super().quit(interaction, button)
this doesn't work, it just sends an interaction error
how can i fix this?
and not because it's hard, because it seems a waste I can do something else
open discord in your web browser or something like that, idk if you can login as a bot account
it seems like a waste of time ngl
isnt it stop and not quit?
nah i dont want to overwrite the one in view, im making my own, i want it to do diff things for diff commands
in this case, i want it to show the select-menu when they click on quit
implementing the button in the subclass, puts the button in the end, i want it in the middle, thats why it has to be implemented in the parentclass
I'll have a stroke trying to understand, goodluck
Same
lmao
Hey, I'm hosting my Discord Bot on my PC and in the console Ignoring exception in command None: discord.ext.commands.errors.CommandNotFound: Command "helps" is not found is often found there when someone puts an incorrect command, how can I make a logging system for error commands that look a lot cleaner?
Use a error handler
Specifically on_command_error
Hello ashley
could i use a cog listner for it?
alright
@commands.Cog.listener(name='on_command')
async def print(self, ctx):
server = ctx.guild.name
user = ctx.author
command = ctx.command
print(f'{server} > {user} > {command}')
what about something like this?
You can use error handlers to send responses in return of errors
the first example is a global error handler and will work for every cog no matter in what cog it is
@commands.Cog.listener("on_command_error")
async def error_h(self, ctx: commands.Context, exc):
if isinstance(exc, ErrorClass): #dont subclass
...
elif isinstance(exc, ErrorClass):
...
or you can use individual error handlers for every command
@commands.command()
async def ping(self, ctx: commands.Context):
await ctx.send("pong")
@ping.error
async def ping_error_h(self, ctx: commands.Context, exc):
if isinstance(exc, ErrorClass): #dont subclass
...
elif isinstance(exc, ErrorClass):
...
Look at Ashley's examples
Hey skev
Find one
in your case
It's commands.CommandNotFound
Or if you import it
It's CommandNotFound
from discord import CommandNotFound
No
!d discord.ext.commands.CommandError
exception discord.ext.commands.CommandError(message=None, *args)```
The base exception type for all command related errors.
This inherits from [`discord.DiscordException`](https://discordpy.readthedocs.io/en/master/api.html#discord.DiscordException "discord.DiscordException").
This exception and exceptions inherited from it are handled in a special way as they are caught and passed into a special event from [`Bot`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot"), [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error").
you can use the ones listed under this section
Missing .ext.commands
import discord.ext.commands
these
Imagine doing that
just use commands.CommandNotFound
I helped as much as I could, its up to them to reply
You can just add commands. to the errror class
Rather than importing everything you need
if isinstance(exc, commands.CommandNotFound):
pass
I like how disnake's docs has the source link besides what you're looking for
hi guys, how can i make this command say the channel?
@commands.Cog.listener()
async def on_message_delete(self, message):
if not message.author.bot and 'server_log' in server_config[message.guild.id].keys():
channel = self.bot.get_channel(server_config[message.guild.id]['server_log'])
if channel:
embed = discord.Embed(title = get_lang(message.guild, 'ADMINISTRATION_serverlog_msgdelete'), description = message.content, color = 0xFFFF00, timestamp = datetime.datetime.utcnow())
embed.set_footer(icon_url = message.author.avatar_url_as(size = 128), text = str(message.author) + ' (' + str(message.author.id) + ')')
await channel.send(embed = embed)
try message.author.user
what
message.channel
i try check the channel
message.channel.name
s
anyone here know how to integrate rich presnce?
!d discord.Client.change_presence
await change_presence(*, activity=None, status=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Changes the client’s presence.
Example
```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
``` Changed in version 2.0: Removed the `afk` keyword-only parameter...
imean
from scratch or smtg , im making the game on renpy
thank you!
!pypi pypresence
it needs python 3.8 , i'm working on 2.7 , idk if renpy can update it tho
Where
look at pypresence src ig
you ever heard of renpy engien?
idont know how to code so im just using it cuz its simple
Nope
We typically help with code issues not with game engines
Games is uh #game-development
its basically discord place here
..
can someone help?
with open("/root/Textfiles/example.txt", "r") as a, open("/root/Textfiles/example2.txt", "r") as b:
if token not in a.read() and b.read():
await ctx.send("Token does not exist")
else:
await ctx.send("Token exists")
This is my code, if the token is the first file (example.txt), then it works fine (says if it exists or does exist), but if the token is in the second file (example2.txt) it always says token does not exist
am i doing something wrong?
@boreal ravine maybe u know
!or-gotcha
When checking if something is equal to one thing or another, you might think that this is possible:
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
no it wont work lmao wait
oh.
ill try it anyway
oh yea it didnt, still same error
the token is there though
if token not in a.read() and token not in b.read()):
this should work, i can't think of anything simpler, i need to go to bed
oh crap yeah someone told me that yesterday but in another context, totally forgot
its actually b.read() not b.read()) xD
PS C:\Users\Micro\Downloads\Canomi> & C:/Users/Micro/AppData/Local/Programs/Python/Python310/python.exe c:/Users/Micro/Downloads/Canomi/main.py
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "set_prefix" is not found
Ignoring exception in command setprefix:
Traceback (most recent call last):
File "C:\Users\Micro\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 181, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\Micro\Downloads\Canomi\cogs\setup.py", line 18, in set_prefix
self.bot.dbmanager.add_guild_prefix(ctx.guild.id, prefix)
AttributeError: 'Bot' object has no attribute 'dbmanager'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Micro\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 360, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Micro\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 927, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Micro\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 190, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'dbmanager'
i have a fle named dbmanager
Are there any caching examples with aioredis?
is there a way of loading files instead of cogs
so u don't import stuff and type more useless junk to load it
thanks it worked
async def on_message(message):
if message.content == "agree":
role = discord.utils.get(Assign.roles, name="Member")
await client.add_roles(message.author.id, role)
I dont know what to change "Assign" in
@iron axle
presumably Assign is supposed to be the Guild that you want to get the Member role from
its not really clear what guild in particular you want though
also client.add_roles is years out of date
oh, what do i need to change it in?
user = ctx.message.author
await user.add_roles(role)
Do you guys have your bots reply to the command message?
That's what I got
they dont have ctx, it would just be message.author
Like would it annoy users?
O: sorry I'm not guna be much help then
How do I import slash commands?
@slash.slash(name="Ping", description="Shows bot latency")
async def pong(ctx):
await ctx.send(f'Pong! - {round(client.latency * 1000)}ms')
Unless it's a slash command, no
👍
from discord import Client, Intents, Embed
from discord_slash import SlashCommand, SlashContext
bot = Client(intents=Intents.default())
slash = SlashCommand(bot)
from discord_slash import SlashCommand?
And the rest of that line, yes
So I should put the
bot = Client(intents=Intents.default())
slash = SlashCommand(bot)
at the place where I defined my bot?
No just the slash = slash thing
Oh okay
No, i think the id should be an int? But ig u need to get_role first
Euhhhhh
!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.
Canibilise this
import discord.utils
@client.command() async def role(ctx, * role: discord.Role): user = ctx.message.author await user.add_roles(role)
Thats a whole new command
And in that u dont even need the "utils" since you already have an arg as a discord.Role
oh okay
so that sould respond to "!role" isnt it?
@iron axle
It will give the author aka the one who used the command
if you're using disnake they already have a slash command implementation so you dont need discord_slash
examples (see param.py): https://github.com/DisnakeDev/disnake/blob/master/examples/slash_commands
docs: https://docs.disnake.dev/en/latest/ext/commands/slash_commands.html
oh so how do I use disnake slash commands
i just sent you the examples and docs
Does it have perms?
yeah, admin perms
Btw remove the role and try again
Is there a simple way to make a command name with 2 words? For example, /nickname set [*args] where nickname set is the command name?
Are u talking abt aliases?
Idk
Wait how do I make aliases?
!d discord.ext.commands.Command
class discord.ext.commands.Command(*args, **kwargs)```
A class that implements the protocol for a bot text command.
These are not created manually, instead they are created via the decorator or functional interface.
aliases=[] in the decorator
Thanks 👍
it can be a tuple too iirc
yeah it can be a list or a tuple
ok
can someone send link of that .json reddit api, idk the name lol
didnt work
i do !role @stray scarab and it doesnt do anythin
Error?
Nope
Add print("done") below await user.add_roles()
i tried, it doesnt print
https://reddit.com/r/subreddit.json?
and no errors
yea thanks
Then it works
yeah
@client.command()
async def role(ctx, * role: discord.Role):
user = ctx.message.author
await user.add_roles(959432789164437606)
print("Done")
so role = "ID HERE"?
No
await user.add_add_role(role)
Just this
He typehinted role so it's already a role object if its valid
and the role id in the last role?
I didnt see that😭😭
No just do add_roles(role)
You already have an arg in ur command which is role
So like this then?
?
No it should be something like```py
@client.command()
async def role(ctx, *, role: discord.Role):
user = ....
await user.add_roles(role)
do i need to fill in anything in the dots?
Yes
ctx.author
ctx.author which is the user who used the command
add_roles not add_add_role
Or you can save a unnecessary variable and use ctx.author.add_roles(role).
LEGENDS
😭😭
rename that to role
this then?
Yess
Oh okay
😭
Somebody help pls? I can't see my cursor in pycharm..
nvm fixed
bru
XD
hehe
error?
nowp
what role are u giving
Member
it is
member, lowest role above everyone
show how u type the command
Can we see the role location?:)
yeah
imagine if member is administrator
no its not haha
Uh guys?
make bot role more up
SlashContext in disnake is?
Dont think so
Why wont my subcommand work?
# Base BTC Command
@commands.group(name = "btc")
async def btc(self, ctx, *args):
if ctx.invoked_subcommand is None:
await ctx.reply(embed = helpEmbed, mention_author = False)
# Address Command
@btc.command(name = "addr", aliases = ["address", "a"])
async def btc_addr(self, ctx, *args):
await ctx.send("Test")
highest one now
ok try
nothing...
Anybody?
No errors, always sends the embed on line #4, even if I add a subcommand.
It should be btc.command
??
whats that?
@slate swan
What do you mean?
SlashContext in disnake is?
idk
Hey I'm new here but any help on making embeds?
uhhh how do I do it mpw
So eh idk how to explain it cuz my brain cell is kinda dead so ye, well it allows u to use extra stuff ig. U need to enable them in discord portal and in ur code
!d discord.ext.commands.group
@discord.ext.commands.group(name=..., cls=..., **attrs)```
A decorator that transforms a function into a [`Group`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group").
This is similar to the [`command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") decorator but the `cls` parameter is set to [`Group`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group") by default.
Changed in version 1.1: The `cls` parameter can now be passed.
well all my other commands like kick and ban worked, so this one should work too isnt it?
Thank you!
np
So when u make a group command btc is like a cog (im just giving example dont mind my words) so u need to do btc.command to add the command to the cog/group command
listen boaz
Ye
@gilded zephyr
Does anybody know what's SlashContext defined as in the disnake libraby?
!d disnake.CommandInteraction
No documentation found for the requested symbol.
huh
Disnake doesnt have SlashInter. It has something like disnake.InteractionApplication
Ig
AppCmdInter
ash help boaz
Got it thanks!
disnake.ApplicationCommandInteraction?
yeah?
!d disnake.ApplicationCommandInteraction
class disnake.ApplicationCommandInteraction```
Represents an interaction with an application command.
Current examples are slash commands, user commands and message commands.
New in version 2.1.
Ye
Oh, thanks legends.
@little ivy ask ash
there are others to help, I will just go away from here
Is there an event where if the user has a certain role
no?
!d discord.on_member_update i mean
discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") updates their profile.
This is called when one or more of the following things change:
• nickname
• roles
• pending...
gtg
No not like that
What's wrong here tho..?
\n
then?
Like e.g if a user has a certain role the do something
You will have to run a task for that
or a command as you wish
@modern fiber it should be user: disnake.Member its bc str doesnt have an id

user: disnake.Member
is there a way of loading files instead of cogs
so u don't import stuff and type more useless junk to load it
dont import then?
🤔🤔
will error
Can i see what client.slash_command looks like?
yup, unclosed parenthesis
where
import os
[bot.load_extension(file[:-3]) for file in os.listdir("./cogs") if file.endswith('.py')]
put your cogs in a folder
look at the first decorator, whats closing the slash_command parenthesis?
Prolly u forgot to close client.slash_command
!d disnake.ext.commands.Bot.load_extensions does it automatically iirc
load_extensions(path)```
Loads all extensions in a directory.
New in version 2.4.
that is, if you are using disnake
?
U forgot to close options
btw some good indentation makes it easier to tell which brackets you're missing
I didn't?
well you've closed your parenthesis before closing the list
U should close it before closing client.slash_commands
@client.slash_command(name="Ping", description="Shows Bot Latency")
async def pong(ctx):
await ctx.send(f"🏓 Pong! ``{round(client.latency * 1000)}ms``")
@client.slash_command(name="Kick", description="Kicks a Member",
options=[
disnake.Option(name="user", description="The user I should kick", required=True, type=disnake.OptionType.channel),
disnake.Option(name="reason", description="Why should I kick them?", required=False, type=disnake.OptionType.channel))
]
@has_permissions(kick_members=True)
async def kick(ctx:disnake.ApplicationCommandInteraction, user: disnake.Member, reason:str="None Given"):
reason = str(reason)
usr = "<@"+str(user.id)+">"
await user.kick(reason)
await user.send("Kicked from "+ctx.guild.name+" for "+reason)
embed = disnake.Embed(title="Kicked a user", description="Kicked "+usr+" for reason: "+reason)
await ctx.send(embed=embed)
print(ctx.author.name+" used: kick")
# ERRORS
@kick.error
async def kick_error(ctx:disnake.ApplicationCommandInteraction, error):
if isinstance(error, PermissionError):
embed = disnake.Embed(title="Permission Error")
embed.add_field(name="Missing:", value="Kick Members")
await ctx.send(embed=embed)
Here, mind showing me please?
what you've essentially written is this
([)]
@client.slash_command(name="Ping", description="Shows Bot Latency")
async def pong(ctx):
await ctx.send(f"🏓 Pong! ``{round(client.latency * 1000)}ms``")
@client.slash_command(name="Kick", description="Kicks a Member",
options=[
disnake.Option(name="user", description="The user I should kick", required=True, type=disnake.OptionType.channel),
disnake.Option(name="reason", description="Why should I kick them?", required=False, type=disnake.OptionType.channel)])
@has_permissions(kick_members=True)
async def kick(ctx:disnake.ApplicationCommandInteraction, user: disnake.Member, reason:str="None Given"):
reason = str(reason)
usr = "<@"+str(user.id)+">"
await user.kick(reason)
await user.send("Kicked from "+ctx.guild.name+" for "+reason)
embed = disnake.Embed(title="Kicked a user", description="Kicked "+usr+" for reason: "+reason)
await ctx.send(embed=embed)
print(ctx.author.name+" used: kick")
# ERRORS
@kick.error
async def kick_error(ctx:disnake.ApplicationCommandInteraction, error):
if isinstance(error, PermissionError):
embed = disnake.Embed(title="Permission Error")
embed.add_field(name="Missing:", value="Kick Members")
await ctx.send(embed=embed)
the list needs to stay inside the parentheses
OH
DAMN IM SO BLIND
Sorry me, young people. Im old.
My eyes don't serve me so well.
its all ight
What is type for the like reason?
whats disnake
library..
yeah bruh
i mean, depends on you, most of the time is optional
Its a dpy fork
!pip disnake
there are more than 10k
so is disnake better then discord.py
OOF
yes
what does it improve
Should I use like string?
no? it might not even work soon
why will disnake keep working then, huh?
read docs, thats why most of the people changed to disnake, nextcord and others
the developer of dpy stopped developing/updating the library so the good ppl started forking the library

ye
What does invoke_without_command do in command groups?
its back under development
discord.py implements Slash in 2.0
It is already working
nextcord/pycord/disnake does it too
Yeah Just wanted to say as he said otherwise
Uhh?
soo... should i change my library to disnake?
preference
disnake's development is faster and has better docs
i mean i want slash commands
you can create those with d.py too
ah yea then im defo switching xD
lmao
oh
though they dont have detailed docs about slashes
uhh
what am I saying
add await ctx.response.defer(with_message = True) 🤔
And easy
ctx 😔
cogs
Its bc he typehinted ctx as a disnake.InteractionCommandApplication
ugh
oh god
Its ApplicationCommandInteraction
lmao
😐
yeah, ive found their documentation about interaction-related stuff fairly confusing
same
inarguable really, the next day i lost the link to the gist ngl
I mean, who would do this
and the fact that they put the app commands into Client
I mean, message commands are not supported by Client, why slashes
well the two are implemented differently, message commands are done with a Client subclass while app commands is done as an addon to the client
ikr, but still
yea it is an inconsistency
Dude why I get this? Isn't showing me any errors
that gist also i think is slowly going out of date, dpy's got better docs on their todo list
@modern fiber
Is it better to have per command, per cog, or global command handling?
error handling*
Where that? 😳
they're already using ctx.send though, so it seems like the command body wasnt executed in the first place
Oh
Mind showing me what I did wrong guys?
@client.slash_command(name="Kick", description="Kicks a Member",
options=[
disnake.Option(name="user", description="The user I should kick", required=True, type=disnake.OptionType.user),
disnake.Option(name="reason", description="Why should I kick them?", required=False, type=disnake.OptionType.string)])
@has_permissions(kick_members=True)
async def kick(ctx:disnake.ApplicationCommandInteraction, user: disnake.Member, reason:str="None Given"):
reason = str(reason)
usr = "<@"+str(user.id)+">"
await user.kick(reason)
await user.send("Kicked from "+ctx.guild.name+" for "+reason)
embed = disnake.Embed(title="Kicked a user", description="Kicked "+usr+" for reason: "+reason)
await ctx.send(embed=embed)
print(ctx.author.name+" used: kick")
# ERRORS
@kick.error
async def kick_error(ctx:disnake.ApplicationCommandInteraction, error):
if isinstance(error, PermissionError):
embed = disnake.Embed(title="Permission Error")
embed.add_field(name="Missing:", value="Kick Members")
await ctx.send(embed=embed)```
ah it should have given a type error since reason is supposed to be a keyword argument, i.e. user.kick(reason='abc')
Do you guys use per command, per cog, or global error handling?
i would go for global error handling first, then have a mechanism to allow local or cog handlers take control if more specific messages are needed
Or a combination of all?
OK I'll keep that in mind, thanks 🙂
Huh? Mind editing this and show me? @hushed galleon
how can i make a GMT+3 timezone for a timestamp? if its possible
Can u show the error?
There is no errors..
by "mechanism", it could just be setting a ctx.handled = True attribute and then checking it in your global/cog error handlers to know if your local error handler already sent a message
I only get this
this code
reason is supposed to be a keyword argument, i.e.
user.kick(reason='abc')
Yes that makes sense
though its weird you're not getting any errors in the console
so I should have an option named keyword not string?
anyone know how to make a GMT+3 timestamp?
Like this or what? Im dumb, my first time using slash commands.
@hushed galleon
Can you please just edit my code? @hushed galleon
i literally wrote an example line of how the user kick should be done
Yeah but I don't understand lmfao
a keyword argument in general python means when you call a function, you type out the full name of the parameter
def add(x, y):
return x + y
# using positional arguments
>>> add(1, 2)
3
# using keyword arguments
>>> add(x=1, y=2)
3```
with Member.kick(), the library developers wrote the function such that the reason is required to be passed as a keyword argument
!d disnake.Member.kick
await kick(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Kicks this member. Equivalent to [`Guild.kick()`](https://docs.disnake.dev/en/latest/api.html#disnake.Guild.kick "disnake.Guild.kick").
^as indicated by documentation with the star * just before the reason parameter
ow
hence why you must write await user.kick(reason='my reason')
nice
im trying to make a gmt+3 timestamp
!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...
Thanks mobile
cause thats my timezone
Use this
your fault
Ik (:
that shows decimals
Huh?
@hushed galleon Like this bruh?
I don't understand cuz you are supposed to write a reason with slash like /kick user reason not write it in the code.
Use the style kwarg
you wont be able to dm the user though
and yes, that should work
you have to dm the user before actually kicking him lol
Yup DM the user before kicking them
what causes this error?
HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In user_id: snowflake value should be less than or equal to 9223372036854775807.
im making a massban command and i tried to ban multiple users using their ids but it gives an error
Wait what the actual-
.
Show code
and you dont have to convert reason to string since you typehinted it as a string and arguments without typehint aare automatically converted to a string, and you can use the mention property on the Member object to ping them instead of making the same thing again and again as <@str(id)>
uhh, how would it be with the style f
@bot.command()
async def massban(ctx, members: Greedy[int], reason=None):
if not members:
await ctx.send("Please specify the users i need to ban.")
else:
list1 = members
for i in list1:
await ctx.guild.ban(discord.Object(id=int(i)))
await ctx.send(f"successfully banned **{len(members)}** user(s).")
thats...
pffftt
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
We ain't helping with that, thanks
im using it to ban raiders not raid 😭
Well 🤷♂️
Is there list of all errors?
is that question for me or
you can always search up the error, or ask for the fix here if u have a problem
No like I mean all discord.py related exceptions?
Yup that's correct ^^^
Sometimes a single error is caused due to number of things
Can I find them on the docs?
I get this again...@slate swan
Yea
👍
Look for the section Exceptions Hierarchy in the docs @gilded zephyr
Should be at the last of the sidebar
Found it thanks a lot 🙂
is it even possible to use gmt+3 timezone on timestamps?
async def kick(ctx: disnake.ApplicationCommandInteraction, member: disnake.Member, reason: str="No reason provided"):
await ctx.response.defer(ephemeral=True)
await member.send(f"You were kicked from *{ctx.guild.name}* for **{reason}**")
await member.kick(reason=reason)
embed = disnake.Embed(title=f"Kicked {member}", description=f"Reason: **{reason}**", color=member.color).set_thumbnail(url=member.display_avatar.url).add_field(name="Kicked By", value=f"{ctx.author.mention}", inline=False)
await ctx.edit_original_message(embed=embed)
@modern fiber
ahem ahem will ignore any pings except lavox
format_dt is the only option
how the hell do i use that
Stop spoonfeeding 😔
!d discord.utils.format_dt bro
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...
U r using the same function in you bio too 👀
im using unix
Eh?
thanks daddy
format_dt literally does the same thing
Lmao what the
will bite
anyone know how to add space in slash command name?
Use invisible symbol
like what
no comments
(ㅤ)
you cant iirc
Can I screenshare you' i can show you it not working bruh
Why doesnt my subcommand work unless I add invoke_without_command = True to the group?
so how do other bot did that
my internet is kinda dumb rn, try using print statements after every line
command groups iirc
ouu, okay thx
wdym?
@has_permissions(kick_members=True)
async def kick(ctx: disnake.ApplicationCommandInteraction, member: disnake.Member, reason: str="No reason provided"):
await ctx.response.defer(ephemeral=True)
await member.send(f"You were kicked from *{ctx.guild.name}* for **{reason}**")
await member.kick(reason=reason)
embed = disnake.Embed(title=f"Kicked {member}", description=f"Reason: **{reason}**", color=member.color).set_thumbnail(url=member.display_avatar.url).add_field(name="Kicked By", value=f"{ctx.author.mention}", inline=False)
await ctx.edit_original_message(embed=embed)
print(ctx.author.name+" used: kick")```
Anybody..?
the problem?
This is the code @slate swan
the full code*
remove the coroutine thats after the function signature
where? can u edit code and send me back?
bro await ctx.response.defer() this
What's a function signature 🗿
It's probably some simple shit and okimii is just trying to make himself seem smarter 🗿
import discord
import os
from discord.ext import commands
client = commands.Bot(command_prefix="!")
@client.command()
async def hi(ctx):
await ctx.send('Yo')
@client.event
async def on_ready():
print('Yo My Creator')
client.run(os.getenv('TOKEN'))```Why is it not work?
bro def function()
thats called and function signature
Where?
bro
any errors?
Bro thats defining the function
he doesn't have to, okimii's smart
🧢
also, I'm gonna start using that word cuz function definition is weird
and I wanna look smarter than I am
@modern fiber r u hosting the bot on yr laptop?
bro didn't i showed you inheritance 😩
nope
show*
No 🗿
i literally showed you subclassing and classmethods
Does it print the on_ready() thing?
No
or does it not startup at all
Nope 🗿
...
dont make me send ss
have u defined the token?
Okay I'm sorry 🗿
🗿
Yes
yes but imma use replit later on

But u havent even imported dotenv?
Sorry if I'm dropping in the middle of something but could someone help me with this?
I have this code:
import discord, os, random, time
TOKEN = os.environ["TOKEN"]
bot.run(TOKEN)
and I'm getting this error:
File "main.py", line 6, in <module>
bot.run(TOKEN)
NameError: name 'bot' is not defined
i dont suggest replit
uh what then? I have no payment method
define bot?
you have to define bot.
you need to define a class instance of the Bot class
how exactly?
bro
...
:D
see the example
and please you don't need to ping me every time you answer
bot = commands.bot(command_prefix=".")
this defines bot, and makes the command prefix .
oh, thank you!
thx to you too!
more like creates an instance of the Bot class which then you create a variable thats literal to the instance hence why it would be defined.
isnt intent required
nope
if you dont need any gateway permissions youre fine
print(message.mentions[0])
except:
await message.channel.send(embed=errorEmbed('Invalid command format', 'promote', message.author))
return
success = False
gm = False
hc = False
if owner == True or manager == True or coach == True:
gmr = discord.utils.get(message.guild.roles, name='General Manager')
hcr = discord.utils.get(message.guild.roles, name='Head Coach')
for i in message.mentions[0].roles:
if nname == i.name:
success = True
if i.name.lower() == 'general manager':
gm = True
if i.name.lower() == 'head coach':
hc = True
print(gmr, hcr)
if gmr == None or hcr == None:
await message.channel.send(embed = errorEmbed('Could not find the correct roles to promote this user.', 'promote', message.author))
if success == True:
if gm == False and hc == False:
await message.mentions[0].add_roles(hcr)
elif gm == True:
await message.mentions[0].add_roles(gmr)
await message.mentions[0].remove_roles(hcr)
lst = 0
for i in message.guild.members:
for b in i.roles:
if b.name == nname.title():
lst += 1
await message.channel.send(embed = tembed(nname, ["Promotion Successful!",
message.mentions[0].name + " has been promoted!"], message.author, ["Roster: ", str(lst) + " people are on this team!"]))
else:
await message.channel.send(embed = errorEmbed('You do not have premission to do this!', 'promote', message.author))
else:
await message.channel.send(embed = errorEmbed('You do not have premission to do this!', 'promote', message.author))```
dude I still get the interaction failed even with this bruh dude
is there any free source mod commands I can see (slash ones)?
pep8 compliance officer?
the problem is that it doesn't even give an error
you should defer your interaction at the start its probably giving the error
@final iron
im hungry for spaghetti
I gave up 🗿
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
Spaghetti code?
yes
See my GitHub then!




