#discord-bots
1 messages · Page 907 of 1
ya and what
cut it out
lmao
Okay that’s enough
ooooo
<@&831776746206265384>
<@&831776746206265384>
!mute 874731032639848488 
:incoming_envelope: :ok_hand: applied mute to @lilac eagle until <t:1647366626:f> (59 minutes and 59 seconds).
handling it
Thank you
gj
.topic
Suggest more topics here!
hmmm
I don’t really like the slash commands to be honest
That part could’ve been handled better
if migrating to slash commands would've provided free hosting/db, i would've flown over
because it seems like a good incentive
Yeah it’s just bots have always functioned the old way for years and out of nowhere they change it
That was probably the last straw for dpy so the entire ecosystem was on fire for a bit after that
which ecosystem, the forks of dpy or the bots?
Bots in general
Since the de facto at the time was dpy and forks weren’t really mainstream
make a pr to my wrapper with how you think they should look
Perhaps
the heck happend
async def paraver(ctx,user:discord.Member, para):
how can I get the user's id ?
hm
then my problem in somewhere different okay thanks
Rename used to member, since user and member are 2 different things
okay I will
https://github.com/CaedenPH/discii/blob/main/discii/errors.py why is their no base exception?
should have a base exception which then gets subclased by other exceptions
Has anyone had a issue, where slash commands disappear after using one of the slash commands..?
why u using slash commands?
Because I want?
Because we’re supposed to migrate
😓
because its not necessary in the slightest
What fork are you using?
disnake
how is it not necessary? youre subclassing Exception and then raising a custom exception from the wrapper which doesn't even have a base exception?
thats like making paint without base colors
(doesn't know art in the slightest)
i think they are called primary colors
or colours
aliases

color == colour
i dont think you know what you're talking about; you copy from discord.py without understanding anything so i'm not going to waste my time getting into a useless argument
!e print('color' == 'colour')
@quaint epoch :white_check_mark: Your eval job has completed with return code 0.
False
!e print('color' < 'colour')
@quaint epoch :white_check_mark: Your eval job has completed with return code 0.
True
im not even talking about dpy are you ok?
colour superiority
ha no
!e print('color' > 'colour')
@quaint epoch :white_check_mark: Your eval job has completed with return code 0.
False
python never lies
its probably comparing the amount of chars in a string lol
!ot btw
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
It is
guessed it loll
oh hey, i fixed the get_bucket but my new issue is
idk how to get the bucket inside the command so i can reset it if i want, any idea?
Just figured that after using slash commands, the bot wants to start upserting all of the slash commands which results them disappearing, but the funny thing is that I'm not registering them globally...
!e
print(0.1 + 0.2 == 0.3)
@cold sonnet :white_check_mark: Your eval job has completed with return code 0.
False
that was taken out of context
!e print((0.1 + 0.2) == 0.3)
@quaint epoch :white_check_mark: Your eval job has completed with return code 0.
False
😅
"python never lies"
lmao

any idea 
!e
print(0.1+0.2)
@honest vessel :white_check_mark: Your eval job has completed with return code 0.
0.30000000000000004
#bot-commands
why 00000000004 tho?
it's because of some binary code impossibilities
python needs to learn math brah
ah
how is this false?
if youre getting the total of 0.1 plus 0.2 and then comparing it to 0.3
'ApplicationCommandInteraction' object has no attribute 'command'
!e
print(round(0.1+0.2, 1))
@honest vessel :white_check_mark: Your eval job has completed with return code 0.
0.3
is it possible to only let a command be usable in the bot dms? and ignore if its used in a server?
yes
ah python is just bad at math
@commands.dm_only
@cold sonnetif not knowing imagine confusion 😄
"i give up coding its too hard for me i change class"
Thank you very much
i need help. its an economy bot using sqlite: https://pastebin.com/RJe4mafJ
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
this is the error i get: Traceback (most recent call last): File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke await ctx.command.invoke(ctx) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke await injected(*ctx.args, **ctx.kwargs) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OperationalError: no such column: getter_id

no such colum exists
what? i just used postbin
Syntax highlighting is shit
i am aware but what did i do wrong
well does that column exists in ur db???
table
cause it sais it dosnt but u still try use it
dbs don't have columns, tables in dbs do
hey guys i want to make discord.js and py docs thx need help
i have tables in dbs
.... ofc but you get it
specification
True
I woke up and chose to be a bitch
😄 fair enough
await cursor.execute("SELECT user_id FROM money_data WHERE user_name = ?", (USER_NAME,))
result_userID = await cursor.fetchone()
if result_userID == None:
await cursor.execute("INSERT INTO money_data(user_name, balance, user_id)values(?,?,?)",(USER_NAME, START_BAL, USER_ID))
await db.commit()
await ctx.send("Hi, you're a new user and you need to register. \nTo register execute the command one more time!")```
this is the code i use to register users
your code dosnt help us
why not?
read the error lol
cause its related to your database -> table -> column
and for py ?
same but dpy
atleast not vuln for sqlinjections
and this channel @faint arrow
so i should show u how i made the table?
hmmm
thats true
you can check if you even have a column called getter_id in money_data table
i could just use ctx.message.author instead to get their username
how?
What did i do wrong? The bot is in the same server as the emoji
idk man i just wanna make this work
@slate swantry add a infront like <a:name:id>
and i would really like to know how to see what columns i have
Still the same, its not an animated emoji btw
sqlite?
maybe the bot doesnt have access to the server that has the emoji
You are in wrong channel #databases @regal cove
yes
thank u
i use that easy n slim
yup
and has both winblows and linux
I mean i gave it all permission as i invited him into that server so i think he should have permission
@slate swandid u do as i said?
yes but it didnt work
there are no errors
yup
it should work - aslong he did put correct id and name
does it have perms? extern emojis?
lol why ask himi just go check
its them 3 possibilites most likley, name, id, permissions
@slate swanalso check the channels permissions
there is both external emojis perms in roles n each channel
Yes it was the id, I just found out that i can do \:emoji-name: and then it just shows you the id 💀
yes
u can do backslash on most things like channels users etc to get ID
@slate swan
thats cool
yes its good to know
otherwise u need to enable developersmode in discord to get Grab ID thing
PRIMETIME and so quiet today is the ww3 on already or what?
anyone know how to add the chose option, on my bot i have the whole embed i just need the select menu idk how to do it
which lib?
here's an example for the first go
How to make that when I ban a member my bot sends a mp to the person to announce him that he was banned ?
await member.send("something")
BEFORE he gets banned in the command
Is there a different wrapper for interactions than interactions-py?
I thought he stopped development of discord.py
resumed
Oh. What happened?
realised he can do it
thanks bro
Does it have slash commands now? And can I use it with discord new requirements?
pycord has nothing new....
How can i get the cooldown with get_bucket (inside the command)
it has create_activity_invite
pov: you switch from slash_util to dpy 2.0 slash commands
luckily managed to fix it fast by using ctrl f and ctrl h
is there a way to respond to 1 message twice? (buttons), button can be used multiple times
How do you switch like easily, can you give me a link/video please
I really need to switch.
its not hard
Yeah so how do I?
Do I need to change a lot? I work in cogs.
@app_commands.command(description = "test")
async def test(self, interaction : discord.Interaction):
await interaction.response.send_message("test")```
this is an example, it came from:
@slash_util.slash_command(description = "test")
async def test(self, ctx):
await ctx.channel.send("test")```
What's the good one?
before: py @slash_util.slash_command(description = "test") async def test(self, ctx): await ctx.channel.send("test")
after: py @app_commands.command(description = "test") async def test(self, interaction : discord.Interaction): await interaction.response.send_message("test")
so ctx is changed to interaction.response
yeah
from discord import app_commands
Can you maybe go dms?
thats all u need to change
how do I respond privately to disnake slash? (i want only the author to see the reponse)
import discord
from discord.ext import commands
from discord import app_commands
class Ping(commands.Cog):
def __init__(self, client):
self.client = client
@app_commands.command()
async def ping(self, interaction : discord.Interaction):
await interaction.response.send_message(f'Pong! **{round(self.client.latency * 1000)}**ms')
def setup(client):
client.add_cog(Ping(client))
``` Anything wrong here?
How does the versioning even work now, I fixed my bot to accommodate for the breaking changes that was made a day or two ago, currently in my requirements file I have mentioned git+https://github.com/Rapptz/discord.py how do I pin it to a version such that breaking changes aren't experienced but bugfixes are?
!d disnake.MessageInteraction.send
await send(content=None, *, embed=..., embeds=..., file=..., files=..., allowed_mentions=..., view=..., components=..., tts=False, ephemeral=False, delete_after=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message using either [`response.send_message`](https://docs.disnake.dev/en/latest/api.html#disnake.InteractionResponse.send_message "disnake.InteractionResponse.send_message") or [`followup.send`](https://docs.disnake.dev/en/latest/api.html#disnake.Webhook.send "disnake.Webhook.send").
If the interaction hasn’t been responded to yet, this method will call [`response.send_message`](https://docs.disnake.dev/en/latest/api.html#disnake.InteractionResponse.send_message "disnake.InteractionResponse.send_message"). Otherwise, it will call [`followup.send`](https://docs.disnake.dev/en/latest/api.html#disnake.Webhook.send "disnake.Webhook.send").
Note
This method does not return a [`Message`](https://docs.disnake.dev/en/latest/api.html#disnake.Message "disnake.Message") object. If you need a message object, use [`original_message()`](https://docs.disnake.dev/en/latest/api.html#disnake.MessageInteraction.original_message "disnake.MessageInteraction.original_message") to fetch it, or use [`followup.send`](https://docs.disnake.dev/en/latest/api.html#disnake.Webhook.send "disnake.Webhook.send") directly instead of this method if you’re sending a followup message.
ephemeral kwarg
aight!
Anyone?
how can i get the current cooldown for a command using commands.Cooldown.Mapping
warning = cursor.execute('SELECT * FROM banwords WHERE userid = ?', (message.author.id,)).fetchone()
2022-03-15T20:51:22.447042+00:00 app[worker.1]: psycopg2.errors.SyntaxError: syntax error at end of input
2022-03-15T20:51:22.447042+00:00 app[worker.1]: LINE 1: SELECT * FROM banwords WHERE userid = ?
2022-03-15T20:51:22.447042+00:00 app[worker.1]: ^
How to fix
any idea how i could send something else to a private channel in that same command?
channel = channel object
await inter.channel.send_message("lol")```
that's what i came up with
would that work ?
mysql or sqlite3?
it says that you cannot import app_commands from discord
What's the easiest way to switch to slash commands if you got normal commands 
didnt use dpy 2 but i believe that u need to get it from something called tree?
postgresql
ah never used that
What else can I use for slash?
im using disnake (dpy fork)
Is there a command to get the author of the message's id?
@bot.command()
@commands.is_owner()
async def alts(ctx, *, ign):
while True:
altFinder = requests.get(f"http://api.antisniper.net/altfinder?key={akey}&name={ign}")
altjson = json.loads(altFinder.text)
for x in altjson['results']:
alist.append(x['ign'])
await ctx.send(alist)```
How do I end the loop, so the bot doesn’t spam the message?
Why are you looping at all
__
__When I joined with an alt I was DM'ed after accepting the rules, what event is that?
@commands.slash_command()
async def purge(self, inter, messages: int = None, author: disnake.Member = None):
channel = inter.channel
await channel.purge(limit = messages, check = author)
successEmbed = disnake.Embed(
name = "Successful!",
description = f"{inter.author.mention} has purged messages."
)
I have this and it results in this error:
Traceback (most recent call last):
File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/disnake/ext/commands/interaction_bot_base.py", line 1332, in process_application_commands
await app_command.invoke(interaction)
File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/disnake/ext/commands/slash_core.py", line 606, in invoke
raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'Member' object is not callable
I'm using Disnake.
You're providing author as the check
You need to provide a callable function checking if the message author id is equal to your author id
Basically I want it so that if author has a value, then it makes the bot delete their messages. If it doesn't have a value, it deletes all the messages in that limit
yes
@client.slash_command(description = "Test command", guild_ids = [])
async def test(inter):
await inter.send("...")```
Hi I'm getting this error```py
The provided arg time is not recognize
The provided arg time is not recognize
Ignoring exception in command user permissions:
Traceback (most recent call last):
File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\ext\commands\core.py", line 185, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Teagan\Documents\Coding\Zupie\bot\cogs\users.py", line 88, in permissions_legacy
await Users(self).permissions_func(ctx, member, channel)
File "C:\Users\Teagan\Documents\Coding\Zupie\bot\utils\helpers.py", line 139, in permissions_func
permissions = channel.permissions_for(member)
AttributeError: 'NoneType' object has no attribute 'permissions_for'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\ext\commands\bot.py", line 1182, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\ext\commands\core.py", line 1495, in invoke
await ctx.invoked_subcommand.invoke(ctx)
File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\ext\commands\core.py", line 904, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\ext\commands\core.py", line 194, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'permissions_for'```in this command https://github.com/SnowyJaguar1034/Zupie/blob/5246e279f16e3aa4cde7adf77f380f4fcd62e0a7/bot/cogs/users.py#L87and I'm not sure why
bot/cogs/users.py line 87
async def permissions_legacy(self, ctx, member: Member = None, channel: Union[TextChannel, VoiceChannel, StageChannel, CategoryChannel] = None):```
What's inter?
can you send a link of the library and how to install etc
channel is None
ty
the docs
could you please help me with something?
can a command be a slash and text command? like py @commands.slash_command() @commands.command() async def foo(ctx): pass
idk
but i dont think that'll work
yeah, but I'm handling that here https://github.com/SnowyJaguar1034/Zupie/blob/5246e279f16e3aa4cde7adf77f380f4fcd62e0a7/bot/utils/helpers.py#L70 and that func gets called https://github.com/SnowyJaguar1034/Zupie/blob/5246e279f16e3aa4cde7adf77f380f4fcd62e0a7/bot/utils/helpers.py#L138
bot/utils/helpers.py line 70
elif isinstance(object_arg, TextChannel): # == "channel"```
`bot/utils/helpers.py` line 138
```py
channel = await interaction_or_context(transaction, channel_arg)```
@quaint epoch
async def callback(*args, **kwargs):
...
@commands.slash_command()
async def foo(...):
return await callback(...)
@commands.command()
async def bar(...):
return await callback(...)
If you want different functionality for each command, abstract the common functionality into it's own function instead of the entire thing
Sorry I'm not going to be able to read that 😅
But it's definitely None when it's called
ah wrong channel sorry
Guys, what event did this come from?
What even can I wait for to see when users are accepting server rules
you get verified its just to check if you are a real user or a bot
Ok but what event is dispatched when we submit this?
They must have listened to a specific event
thats just some security thing from gernerally discord
Ok but what websocket event did the python bot listen for that
there are two i think they really want to make sure that there are no bot or something
When submitting, you get a DM from the Python bot.
What websocket event is that?
hey uh how do i send a message to another channel when using slash commands? (disnake)
I understand what it's there for, but what event is it?
phu i think thats a a command or a on_ready event
ik i'v seen docs for it before, just can't find them now
intents = discord.Intents.all() @bot.event async def on_member_join(member): await member.send('')
something like this
Ohh it's on_member_update
that could be thanks
could i make something to send a message throught the terminal?
hey uh how do i send a message to another channel when using slash commands? (disnake)
import disnake
from disnake.ext import commands
class Ping(commands.Cog):
def __init__(self, client):
self.client = client
@client.slash_command(name='Ping',description='Test ')
@commands.command()
async def ping(self, inter):
await inter.response(f'Pong! **{round(self.client.latency * 1000)}**ms')
def setup(client):
client.add_cog(Ping(client))
``` Would this work?
await inter.response.send_message
await inter.send()
```Is enough
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
i just do "if message.content.startswith("thing")"
how does that work exactly
bot != client, client is for events only and bot is for commands and events.
The same as client but instead of using the Client class you use Bot
oh, my bot doesnt have any of that
@command(*args, **kwargs)```
A shortcut decorator that invokes [`command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command "discord.ext.commands.GroupMixin.add_command").
do i do this at the beginning of the code?
or substitute it for the "if message.content.startswith(a):"
how do I decode permissions value
ye
help
No you use the class of Bot
it says invalid syntax
Here is an example https://github.com/Rapptz/discord.py/blob/master/examples/basic_bot.py
can i just turn intents off like this:
intents=false
bot = commands.Bot(command_prefix='>', description="idk", intents=False)```
now what?
you only need bot
delete client
intents defaults to None already
ahhh thanks
message send
no, its set to intents.default()
hence why its called default

No it was member update
you're talking about when a message is dm'd, right?
no
If you read my convo there you'll understand it
I already found my answer, thank you
discord/state.py line 216
intents = options.get('intents', None)```
warning = cursor.execute('SELECT * FROM banwords WHERE userid = ?', (message.author.id,)).fetchone()
2022-03-15T20:51:22.447042+00:00 app[worker.1]: psycopg2.errors.SyntaxError: syntax error at end of input
2022-03-15T20:51:22.447042+00:00 app[worker.1]: LINE 1: SELECT * FROM banwords WHERE userid = ?
2022-03-15T20:51:22.447042+00:00 app[worker.1]: ^
postgresql
Hot to fix?
async def react(ctx):
await ctx.message.add_reaction(":soccer:")```
this does nothing
this does nothing
Try using \⚽
I recomend using asyncpg for postgresql with your discord bot
Ok
any reason you use that instead of psycopg2 ?
It's asyncronous
psycopg2 has async options but asyncpg is better overall and more used.
well from what I've read so is psycopg2? I see a lot of bots use asyncpg but whenever I google postgres python packages i only get psycopg2 results so I was under the impression asyncpg was discontinued or something
Oh I haven't seen async side of psycopg2
Always used asyncpg, never seen anything better 🤷♀️
oh okay weird, that does not line up from my research experience on the topic
My first and third options are asyncpg
again, weird. that'll be google search for you I guess, musta searched psycopg2 sometime in the past and now it loves showing me those results
afaik google searches are always the same when it comes to ranking
Since incognito has the same results
I think when it comes to deciding on what libraries to use it's best to ask other people than to rely on google searches, as often the sturdiest and best libraries will be loved by many and recommended, I think this is a perfect demonstration of that

okay so I have this command which can take a optional member argpy @legacy_user_group.command(name ="info", description=info_description, usage="[member]", aliases=["whois", "ui"]) async def info_legacy(self, ctx: commands.Context, member: Union[Member, User] = None): await Users(self).info_func(ctx, member)I then pass the inputs into this function in a custom classpy async def info_func(self, transaction, member_arg): member = await interaction_or_context("MEMBER", transaction, member_arg) member_status = "No status" if member.activity is None else member.activity.name embed = Embed(title = f"{member}", description = f"Status: **{member.status}**\n*{member_status}*", colour = member.colour) embed.set_author(name = f"{member.id}", icon_url = member.avatar.url) embed.set_thumbnail(url = member.avatar.url) await self.timestamps_func(member, embed, True) roles = [f"{role.mention}" for role in member.roles] if len(roles) == 0: roles.append("No roles") has_key = [perm for perm in bot_var.config.key_perms if getattr(member.guild_permissions, perm)] if len(has_key) == 0: has_key.append('No permissions') embed.add_field(name = f"Roles: {len(roles)}",value = f"{len(roles)} roles" if len(" ".join(roles)) > 1000 else " ".join(roles), inline = False) embed.add_field(name =f'Key permissions', value = ", ".join(has_key).replace("_"," ").title(), inline = False) await interaction_or_context(transaction, embed)at this point member_arg should be either a member or None (I think). This function then calls another function and sets the member var equal to the result of the function. As the code shows I am passing in three arguments to this second func, those being "MEMBER, transaction and member_arg, this function ispy async def interaction_or_context(arg_type, transaction, object_arg): if arg_type == "MEMBER": if isinstance(transaction, Interaction): member = transaction.user if object_arg is None else object_arg elif isinstance(transaction, Context): member = transaction.author if object_arg is None else object_arg else: print("ERROR: interaction_or_context : Hit ele statemnt in 'MEMBER' check") return memberbut for some reason i get an error saying the object_arg param is missing, is that bc it's None?py Ignoring exception in command user info: Traceback (most recent call last): await injected(*ctx.args, **ctx.kwargs) # type: ignore File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\ext\commands\core.py", line 194, in wrapped raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: interaction_or_context() missing 1 required positional argument: 'object_arg'
No, you're just not passing it
see:
await interaction_or_context(transaction, embed)
oh oof, thought I'd caught all of those sending ones
Also as nice as comprehensions are the info_func is quite unreadable.
yeah I did that in various channels across a few days in both this server and d.py and my msgs always got missed/ignored which is why i went to google
How do you make it use slash commands
in what way, in it's layout or the use of multiple funcs? I always welcome feedback
what library are you using? some of them do it differently altho they seem to be rather similar
oh discord has slash commands under discord.app_commands not discord.ext.commands and you need to be using the master branch of discord.py to have slash commands as a feature, the stable version on pypi doesn't have them just yet
so what do i do
you need to create them,
examples for discord.py slash cmds is here https://gist.github.com/Rapptz/c4324f17a80c94776832430007ad40e6
slash commands are unique, you essentially need to recreate your commands into slash cmds.
that said, I'd recommend switching to a fork with a more stable implementation of slash commands, such as disnake https://guide.disnake.dev/
if you want to continue using discord.py then you can download the latest master branch like thisshell pip install -U git+https://github.com/Rapptz/discord.pybut as madbard said you could switch to a different fork. Disnake is the one I would recommend based on what I've read of it's docs but I've never actually used it bc I made the decision to move to hikari a week before d.py got revived so I just moved back to d.py
and i will just say the implementation of d.py's slash commands have changed a bit since that gist was posted so some of the examples don't work quite like they do there, if you didn't know
customRole = await find_by_name(role, ctx.message.guild.roles)
emoji = await find_by_name(customRole.name, ctx.message.guild.emojis)
embed = discord.Embed(title=f'Role {customRole.name} Roster', description=f"{emoji.name}{customRole.mention}" , color=customRole.colour)
embed.add_field(name=f'Team Staff:', value=f">>> FO:{', '.join(FO)}\n GM:{', '.join(GM)}\nHC: {', '.join(HC)} ", inline=False)
embed.add_field(name="Players", value=f"{customRole.name} Players: \n >>> {', '.join(CUSTOM)} ", inline=True)
embed.set_author(name=f"{ctx.guild}", icon_url=str(ctx.guild.icon_url))
embed.set_thumbnail(url=str(emoji.url))
embed.set_footer(text=f"Roster Count:\n {len(CUSTOM)}/30 \n")
await ctx.send(embed=embed)
``` error emoji object is not Subscriptable
they dont work..
anyone got a example of autocomplete I could look at (I mean autocompletes in use not the code for it)
what isn't working, can you show any errors and/or any code
Nvm it was me being dumb
! DiscordUtils
which line?
How do I make a check where if a member is mentioned in author, it'll delete messages from only that user and if there's nothing there, it deletes however many messages?
@commands.slash_command()
async def purge(self, inter, messages: int = None, author: disnake.Member = None):
channel = inter.channel
await channel.purge(limit = messages, check = author)
successEmbed = disnake.Embed(
name = "Successful!",
description = f"{inter.author.mention} has purged messages."
)
if author should do the job
if author is not None:
# do something
else:
# do something else
Ok, ty
async def purge(self, inter, messages: int, author: disnake.Member = None):
channel = inter.channel
def checks():
if author != None:
return message.author = author
else:
return None
deleted = await channel.purge(limit = messages, check = checks, bulk = True)
successEmbed = disnake.Embed(
name = "Successful!",
description = f"{inter.author.mention} has purged {len(deleted)} messages."
)
@slim ibex this doesn't work, I think I fucked it, like 100% defo fucked it. Any help?
Traceback (most recent call last):
File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/disnake/ext/commands/interaction_bot_base.py", line 1332, in process_application_commands
await app_command.invoke(interaction)
File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/disnake/ext/commands/slash_core.py", line 606, in invoke
raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Purge.purge.<locals>.checks() takes 0 positional arguments but 1 was given
I get this error when I run the command:
/purge messages: 1
that isn't what you do ...
this has nothing to do iwth check()
its literally an if statement
you should be able to implement your logic by checking if author is None or not
Yeah, and I've put
if author != None:
How do I use the traceback module? someone suggested I print the full traceback of an error rather than just saying an error occurred and its destination. I have this so farpy print(f"\nFailed to Load Extension {extension}\n{traceback.print_exc()}\n")but it just prints outpy Failed to Load Extension cogs.help None
!= isn't the same as is not
That's not what my computer science teacher taught me lmao
!= checks for equality. is not checks for identity
if not author:
use this for booleans^
^
Traceback (most recent call last):
File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/disnake/ext/commands/interaction_bot_base.py", line 1332, in process_application_commands
await app_command.invoke(interaction)
File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/disnake/ext/commands/slash_core.py", line 606, in invoke
raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Purge.purge.<locals>.checks() takes 0 positional arguments but 1 was given
I keep getting this.
as binds said is is used for comparing ids or entities while == checks for values
pretty cool thing in py iirc 256 and 257 arent the same entities so comparing them with is would be false and if you compare a number with a lowerr thrn that range it returns true
Wdum? If I don't have a check, it deletes all the messages without checking if the author of the message is the person who's messages I want to delete
lemme check the docs since I never used this 
(I'm using Disnake btw)
!d discord.TextChannel.purge
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.
Changed in version 2.0: The `reason` keyword-only parameter was added.
Examples
Deleting bot’s messages...
can someone help me out? My code isnt working and I am new to discord.py ```python
import discord
from discord.ext import commands
#server_id = "922146486840590367"
def read_token():
with open("token.txt", "r") as f:
lines = f.readlines()
return lines[0].strip()
token = read_token()
bot = commands.Bot(command_prefix='?')
client = discord.Client()
@bot.command()
async def ping(ctx):
await ctx.send("working")
@client.event
async def on_member_join(member):
for channel in member.server.channels:
if str(channel) == "general":
await client.send_message(f"""Welcome to the server {member.mention}""")
@client.event
async def on_message(message):
id = client.get_guild(922146486840590367)
channels = ["bot-command-channel"]
if str(message.channel) in channels:
if message.content == "?hello" and message.content != -1:
await message.channel.send("HELLO!")
if message.content == "?total_users" and message.content != -1:
await message.channel.send(f"""Number of Members: {id.member_count}""")
bot.add_command(ping)
client.run(token)this is the error
Traceback (most recent call last):
File "C:/Users/joelj/PycharmProjects/UndBot/BotMain.py", line 38, in <module>
bot.add_command(ping)
File "C:\Users\joelj\anaconda3\envs\undbot\lib\site-packages\discord\ext\commands\core.py", line 1149, in add_command
raise CommandRegistrationError(command.name)
discord.ext.commands.errors.CommandRegistrationError: The command ping is already an existing command or alias.```
Remove bot.add_command
so this is the proper check if author = ctx.author
def check(m):
return m.author == author
but then my command wont work
change client.event to client.listen
sure
If you have @bot.command() in the command, then it makes it a command. Plus, it's in your main.py / main file
It's trying to register the command twice
ahhh
Doesn't that check against the person who called the command?
what's you're code again?
@commands.slash_command()
async def purge(self, inter, messages: int, author: disnake.Member = None):
channel = inter.channel
def checks():
if not author:
return message.author == author
else:
return None
deleted = await channel.purge(limit = messages, check = checks, bulk = True)
successEmbed = disnake.Embed(
name = "Successful!",
description = f"{inter.author.mention} has purged {len(deleted)} messages."
)
That's the code, I haven't implemented any new checks yet
it says this now Traceback (most recent call last): File "C:/Users/joelj/PycharmProjects/UndBot/BotMain.py", line 19, in <module> @client.listen AttributeError: 'Client' object has no attribute 'listen'
for your case try:
def checks(m):
if not author:
return m.author == author
else:
return None
not sure if this'll work tho @modest plover
Ok, well, it's sending the message but it isn't deleting messages if I don't have the author option with a value
Or in general
It doesn't delete messages.
even though author is not None?
@commands.slash_command()
async def purge(self, inter, messages: int, author: disnake.Member = None):
channel = inter.channel
def checks(message):
if not author:
return message.author == author
else:
return None
deleted = await channel.purge(limit = messages, check = checks, bulk = True)
successEmbed = disnake.Embed(
title = "Successful!",
description = f"{inter.author.mention} has purged {len(deleted)} messages."
)
await inter.response.send_message(embed = successEmbed)
!d discord.TextChannel.purge
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.
Changed in version 2.0: The `reason` keyword-only parameter was added.
Examples
Deleting bot’s messages...
def checks(message):
if author is not None:
return message.author == author
else:
return None
try this^
Man I got confused 🤦♂️
useless else statement
that is literally what I told you to do before @modest plover
you need to check for author’s identity and put your logic in the statements
\🗿
In this situation I think doing *, author: Member = None would be useful so all arguments after messages are related to the member to delete messages for, if author is not None
why not return True lol
not sure if a List[Member] typehint would be warranted here. It could be though as you could interpret it as a list of members, but since * makes all arguments after it correspond to the parameter after, it probably isn’t needed
I just changed the part where there was a mistake and ignored the rest \🗿
^
you subclass the Cog class
i have
@commands.command()
@commands.has_permissions(ban_members = True)
@commands.cooldown(1, 2, commands.BucketType.user)
async def unban(self, ctx, member: BannedMember):
user = discord.user
await ctx.guild.unban(member.user)
unbanmsg = discord.Embed(color = 0x2ecc71, description = f":msuccess: {member.user} has been successfully unbanned by {ctx.message.author.mention}")
await ctx.send(embed = unbanmsg)
and also
class BannedMember(commands.Converter):
async def convert(self, ctx, argument):
if argument.isdigit():
member_id = int(argument)
try:
return await ctx.guild.fetch_ban(discord.Object(id = member_id))
except discord.NotFound:
raise commands.BadArgument("This member has not been banned before.") from None
ban_list = await ctx.guild.bans()
entity = discord.utils.find(lambda u: str(u.user) == argument, ban_list)
if entity is None:
raise commands.BadArgument("This member has not been banned before.") from None
return entity
the command doesn't work
you subclassed Converter bro
and you need an initiate in the Cog so you can pass the Bot instance
i tried it inside the commands.Cog and outside next to the imports
i do have intiate
bot.load_extension(f'Data.Commands.{filename[:-3]}')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
C:\Users\acali\OneDrive\Desktop\discord.py bots\Wordy\main.py:31: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
bot.load_extension(f'Data.Events.{filename[:-3]}')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
how come im getting this error
for filename in os.listdir('Data/Commands/'):
if filename.endswith('.py'):
try:
bot.load_extension(f'Data.Commands.{filename[:-3]}')
except Exception as e:
print(e)
for filename in os.listdir('Data/Events/'):
if filename.endswith('.py'):
try:
bot.load_extension(f'Data.Events.{filename[:-3]}')
except Exception as e:
print(e)``` this is my code
mains method is now a coroutine
read the error
so i'd await it right
yes
but its not a function so how would i do it
Did you override the bot.load_extension
idk
is it a coroutine in main?
yeah
because in main adding a cog is a coroutine now
async def main():
async with bot:
await bot.start("token")
how would i await tho if its not in a function
not an async function
just do it normally
File "C:\Users\acali\OneDrive\Desktop\discord.py bots\Wordy\main.py", line 24
await bot.load_extension(f'Data.Commands.{filename[:-3]}')
^
SyntaxError: 'await' outside function```
btw why are you using context managers lol
you cant call a coroutine outside of a coroutine
imagine if python supported top level await like JS
top level by?
outside of async functuons
but still not in sync functions
you could use await in the global scope (top-level)
you can use asycnio.run()
ah so you mean you can call coroutines outside of coroutines in js?
promises*
pardon?
let foo = await fetch("...");
coroutines in js are promises
i cant keep promises but i can keep coroutines 👁️ 👁️
"hey man you need to use a promise"
kek
let foo = await fetch("...");
async function bar() {
await fetch("...");
}
well the foo declaration works because JS supports top level await
so youre calling pythons await low level, i find that offensive 
top-level isn't related to high or low level langs lol
the top level of any language is the global scope
well get it in 4.10🗿
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
dont be that guy'

smh
Traceback (most recent call last):
File "C:\Users\culan\OneDrive\Desktop\echo slash\echo.py", line 40, in <module>
asyncio.run(new())
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "C:\Users\culan\OneDrive\Desktop\echo slash\echo.py", line 36, in new
await bot.tree.sync(guild=discord.Object(479997589790523405))
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\tree.py", line 861, in sync
raise ClientException(APP_ID_NOT_FOUND)
discord.errors.ClientException: Client does not have an application_id set. Either the function was called before on_ready was called or application_id was not passed to the Client constructor.``` I'm struggling to figure out how to fix this issue I'm running the new version of discord.py
the error is so specified 😔
so can i subclass a class inside a cog?
And maybe specific but I can't figure out how to fix it
Never encountered something like this
Now I feel like I shouldn't switch hunai to dpy
nested classes?
Interesting and learning curve which I'm over here struggling with new version
class BannedMember(commands.Converter):
async def convert(self, ctx, argument):
if argument.isdigit():
member_id = int(argument)
try:
return await ctx.guild.fetch_ban(discord.Object(id = member_id))
except discord.NotFound:
raise commands.BadArgument("This member has not been banned before.") from None
ban_list = await ctx.guild.bans()
entity = discord.utils.find(lambda u: str(u.user) == argument, ban_list)
if entity is None:
raise commands.BadArgument("This member has not been banned before.") from None
return entity
``` how am i supposed to get this to work inside my cog
Yes there are loads of changes
class Moderation(commands.Cog):
__slots__ = ('bot')
def __init__(self, bot):
self.bot = bot
ah yeah you could
@commands.command()
@commands.has_permissions(ban_members = True)
@commands.cooldown(1, 2, commands.BucketType.user)
async def unban(self, ctx, member: BannedMember):
user = discord.user
await ctx.guild.unban(member.user)
unbanmsg = discord.Embed(color = 0x2ecc71, description = f":msuccess: {member.user} has been successfully unbanned by {ctx.message.author.mention}")
await ctx.send(embed = unbanmsg)
There's some cool stuff in it but I can't even get my main file to work I've been working on it for 3 days now I think this is the last issue but haven't successfully fixed it yet
Anybody have an idea on how I can fix this?
They said it's an obvious fix and wouldn't help me
So yeah it wants to buy ID but how and where and why it's never required this before
it takes a guild id if given
if not then it'll take an hour or so to sync it to all the bot's server's
It's got the id of it though but it's asking for a bot ID in that error isn't it
its asking for a guild id
but its optional
It's got one
They told you what to do
lol
Does it mean it's helping me
That's why I'm still here asking for help
It's pretty clear
application_id is automatically fetched after your bot connects, so i believe you can alternatively do a startup task that waits until the bot is ready and then sync then
Conveniently all the examples that were put out are missing that 😐
user = discord.user
await ctx.guild.unban(bannedMember.user)
unbanmsg = discord.Embed(color = 0x2ecc71, description = f":msuccess: {member.user} has been successfully unbanned by {ctx.message.author.mention}")
await ctx.send(embed = unbanmsg)
why is the embed never sent?
member is unbanned, but the embed is never sent, if you can help ping me please
is this the right place to get help with webhooks
do you have an on_command_error handler? and can you send the code for the entire command? it seems you're referencing two variables bannedMember and member which you probably intended to be the same
i figured out what happened lol
its supposed to be bannedMember.mention, member was the string input
hm but you didnt see an AttributeError in your terminal?
nope i suppressed all errors lol
those tracebacks are pretty helpful at debugging code
sounds like a good workflow
yeah
if you mean the webhooks in discord
im trying to set up a weebhook with my Nolt page (i have no idea how to use webhooks)
in Nolt you are given the following options:
Endpoint URL
Verify Token (optional)
Singing Secret (optional)
everything I try returns error 400
is this related to a discord bot?
it seems to be an api issue
it's an api thing. ive got no idea where to get API support though
this is the closest place i could think of
#web-development would be closer i recommend you to claim a help channel
thank you 🙏
I'm still unable to get my game/status to change as well as my commands to sync
Upon further inspection it does not seem to be running that part of the code
async def main():
async with bot:
await bot.load_extension('cogs.botut')
async with bot:
await bot.start("")
async def new():
print("test3")
async with bot:
print("test2")
await bot.tree.sync(guild=discord.Object(479997589790523405))
print("test1")
await bot.change_presence(status = discord.Status.dnd, activity = discord.Game('/help | echobot.xyz/testing'))
print("test")
asyncio.run(main())
asyncio.run(new())
you cant have two asyncio.run() calls since bot.start() is supposed to never return, so it doesnt reach new()
also weird that you have two nested async with bot:
Indeed
Since when does Bot implement _aenter_ 
!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.
I was following the basic structure inside of the gist but how do you recommend I do this thing?
Ignoring exception in command tree:
Traceback (most recent call last):
File "/home/ubuntu/.local/lib/python3.9/site-packages/discord/app_commands/tree.py", line 693, in wrapper
await self.call(interaction)
File "/home/ubuntu/.local/lib/python3.9/site-packages/discord/app_commands/tree.py", line 773, in call
raise CommandNotFound(name, parents)
discord.app_commands.errors.CommandNotFound: Application command 'wallpaper' not found``` i keep getting this error even when the slash command exists and works fine, im not running my bot twice or anything it just errors, even though the slash command works and responds fine
dpy 2.0 was recently redesigned to acquire the event loop through the context manager rather than just using get_event_loop() on construction
Oh i see
https://paste.pythondiscord.com/ofiselusac
why does this don't work?
it doesn't show any errors and doesn't send the goodbye message set
for setting the initial presence, you can pass the activity and status in the bot constructor which will be sent to discord during the IDENTIFY payload, or in other words when you start the bot py bot = commands.Bot( status=discord.Status.dnd, activity=discord.Game(...) )
so this ? bot = commands.Bot(command_prefix='!', status=discord.Status.dnd, activity=discord.Game(...))
what about my sync tho
that can go in an async task that waits until the bot is ready, like i mentioned before
e.g. ```py
async def sync_commands(bot):
await bot.wait_until_ready()
# Sync global commands
await bot.tree.sync()
# Sync guild commands (note: can make a lot of API calls)
for guild in bot.guilds:
await bot.tree.sync(guild=guild)
async def main():
# run sync_commands in the background
asyncio.create_task(sync_commands(bot))
async with bot:
await bot.start(...)```
you can also put the syncing inside setup_hook(self) if you subclassed bot
bot = commands.Bot(command_prefix='!',
status=discord.Status.dnd,
activity=discord.Game(...))
bot.remove_command('help')
@bot.event
async def on_ready():
print("-------------Bot-------------")
print('The bot is ready!')
print(bot.user.name)
print(bot.user.id)
async def sync_commands(bot):
await bot.wait_until_ready()
await bot.tree.sync()
for guild in bot.guilds:
await bot.tree.sync(guild=guild)
async def main():
async with bot:
await bot.load_extension('cogs.botut')
asyncio.create_task(sync_commands(bot))
async with bot:
await bot.start("")``` so all togethr this?
you dont need the nested async with
also ig you dont need the bot parameter for sync_commands since you've defined it as a global variable
Ignoring exception in command continents:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/new-server/continent.py", line 24, in continents
continent = discord.Embed(
NameError: name 'embed' is not defined
code :-
@commands.command()
async def continents(self, ctx):
continent = discord.Embed(
title=f'Get your continent role here',
color=0x530101,
description=
"  <@&934015812203855933> \n  <@&934016254472224809> \n  <@&934016343995473920> \n  <@&934016472391483412>"
)
.................
and also i assume you intended to pass a name for your activity?
ya i will
who wants tictactoe code for bot
so the frist one in main?
the error shows embed lowercase which doesnt seem to match your code; did you reload the cog after editing it?
yeah
yes
shall i do it again ?
bot = commands.Bot(command_prefix='!',
status=discord.Status.dnd,
activity=discord.Game('/help | echobot.xyz/testing'))
bot.remove_command('help')
@bot.event
async def on_ready():
print("-------------Bot-------------")
print('The bot is ready!')
print(bot.user.name)
print(bot.user.id)
async def sync_commands(bot):
await bot.wait_until_ready()
await bot.tree.sync()
for guild in bot.guilds:
await bot.tree.sync(guild=guild)
async def main():
await bot.load_extension('cogs.botut')
asyncio.create_task(sync_commands(bot))
async with bot:
await bot.start("")```
future: <Task finished name='Task-2' coro=<sync_commands() done, defined at C:\Users\culan\OneDrive\Desktop\echo slash\echo.py:28> exception=Forbidden('403 Forbidden (error code: 50001): Missing Access')>
Traceback (most recent call last):
File "C:\Users\culan\OneDrive\Desktop\echo slash\echo.py", line 32, in sync_commands
await bot.tree.sync(guild=guild)
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\tree.py", line 868, in sync
data = await self._http.bulk_upsert_guild_commands(self.client.application_id, guild.id, payload=payload)
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 496, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access``` i get this tho
uhh, did you invite your bot with the application.commands scope?
🤦 I forgot I am using a test bot
also i would suggest doing this sync in some command so it isnt being called whenever you're just restarting the bot for hotfixes
What do you mean
you'll probably find a time where you're restarting the bot several times, and discord may ratelimit you if you keep trying to sync your slash commands, even if you havent added any new ones
And how do you fix that?
doing this sync in some command
Hey Guys, My !gen1 isnt working here is my code
`@client.command()
async def pop_random_line():
''' picks a random line from a file, then deletes the line '''
with open("keys.txt", "r") as file:
lines = file.readlines()
chosen_index, chosen_line = random.randrange(0, len(lines))
with open("keys.txt", "w") as file:
del lines[chosen_index]
file.writelines(lines)
return chosen_line
@client.command()
async def gen1(ctx):
line = random.choice(lines)
await ctx.send(line)
`
i.e. on demand, whenever you want to sync it
So just adding the sync to the command?
is there a fix for this
@sly hamlet u new with python?
yeah, just write an owner-only command for yourself
whats ur error
my command dosent work
Nope normally only develop small games in it been doing my Discord but for a while now but I stopped doing it when they announced that discord.py would not be updating any more some of it out of practice I also like asking a lot of questions for clarification also with my learning and reading disability it's not always easy for me
Okay I will make that in my notes to do tomorrow thank you very much for all your help I'mma call it for tonight
when i type !gen1 nothing happens
@client.command()
async def pop_random_line():
''' picks a random line from a file, then deletes the line '''
with open("keys.txt", "r") as file:
lines = file.readlines()
chosen_index = random.randrange(0, len(lines))
chosen_line = lines[chosen_index]
with open("keys.txt", "w") as file:
del lines[chosen_index]
file.writelines(lines)
return chosen_line
@client.command()
async def gen1(ctx):
line = pop_random_line()
await ctx.send(line)
Try with this exact code, your code you posted there has errors
And even if it doesn’t work like this, the other code still isn’t correct and you shouldn’t revert back to it
my !gen1 doesnt work
Ok, but don’t revert back to this code, it won’t work
alr
@commands.command()
async def continents(self, ctx):
continent = discord.Embed(
title=f'Get your continent role here',
color=0x530101,
description=
"  <@&934015812203855933> \n  <@&934016254472224809> \n  <@&934016343995473920> \n  <@&934016472391483412>"
)
.......
Error
Ignoring exception in command continents:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/new-server/continent.py", line 52, in continents
await ctx.send(embed=continent, components=continent)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_slash/dpy_overrides.py", line 323, in send_override
return await send(channel, *args, **kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_slash/dpy_overrides.py", line 234, in send
embed = embed.to_dict()
AttributeError: 'list' object has no attribute 'to_dict'
my !gen1 doesnt work at all when you type it nothing happens
`@client.command()
async def pop_random_line():
''' picks a random line from a file, then deletes the line '''
with open("keys.txt", "r") as file:
lines = file.readlines()
chosen_index = random.randrange(0, len(lines))
chosen_line = lines[chosen_index]
with open("keys.txt", "w") as file:
del lines[chosen_index]
file.writelines(lines)
return chosen_line
@client.command()
async def gen1(ctx):
line = pop_random_line()
await ctx.send(line)`
whats ur error? commandnotfound?
not gettign an error
my code runs fine but when you type the command it doest work
anyone ?
how would i get a guilds set vanity url with the id?
With an ID you can get the guild object using either bot.get_guild() or bot.fetch_guild() depending on whether or not said guild is cached. Once you have the guild object, you can call the vanity_invite() coroutine on it
components?
why is there an @client.command() on top of pop_random_line()?
is it possible to format text in RichEmbed description?
like making it bold or underline
yes if it is in the description
how tho
just use normal discord formatting?
yes
like "`"
like this
*like this*
how to take ss of a website using python ???
just like alpha bot which is available in different crypto discord server which take ss of trading view i want thing
can anyone guide me how it can be possible ?
okok thxx
u can use the screenshot api
just google it
send a request to https://image.thum.io/get/https://discord.com
discord.com is a placeholder
thx but this gave me entire website
i want a portion of it
Crop the image
What's this?
🤣 what the
I'd conclude that discord doesn't want anyone screenshotting anything using an api
Given the ban in the <p>tag
Can we see our bot's dms for who dmed it what?
Yes
yes
How?
on_message
!d discord.Client.private_channels
property private_channels```
The private channels that the connected client is participating on.
Note
This returns only up to 128 most recent private channels due to an internal working on how Discord deals with private channels.
Me dumb, can you link me somewhere so i can copypasta?
Oooo
What am I supposed to do?
I can't host my bot
just wait for the ratelimit to end
Ok
Wait, because repl.it has literally thousands of containers NATed on one machine, all of which are probably also people trying to host their discord bot
@client.event
async def on_message(message):
await client.process_commands(message)
if not message.guild:
#do stuff
Ip ratelimited easily
Ok thanks
Tysm
Modmail?
No, im trying to see who dmed my bot, just for fun
Oh ok xD
2022-03-16T06:20:52.541813+00:00 app[worker.1]: Traceback (most recent call last):
2022-03-16T06:20:52.541840+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/nextcord/ext/commands/bot.py", line 1052, in invoke
2022-03-16T06:20:52.541841+00:00 app[worker.1]: await ctx.command.invoke(ctx)
2022-03-16T06:20:52.541855+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/nextcord/ext/commands/core.py", line 933, in invoke
2022-03-16T06:20:52.541856+00:00 app[worker.1]: await injected(*ctx.args, **ctx.kwargs)
2022-03-16T06:20:52.541870+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/nextcord/ext/commands/core.py", line 177, in wrapped
2022-03-16T06:20:52.541870+00:00 app[worker.1]: raise CommandInvokeError(exc) from exc
embed.add_field(f"Giveaway ends in {time}")
help
@worldly bane sorry for ping
👋🏼
wait
ok
how to make prefix so it works in both uppercase and lowercase
bot = commands.Bot(command_prefix='hi','HI', help_command=None, intents=intents)
might work or not
bot = commands.Bot(
command_prefix=("a", "A"))
not helping
??
ok
hmm
i see
simply add_field requires name and value and you just gave name
hmm
probably uses shared IPs if it's free
The Core Hosting Panel. This link will not let you log in unless you have an account. Click the discord button in the top right of the login page and use our manager bot to get set up.
Imagine making a bot just to set users up....
guys
.cf
yeah
Whats wrong with that?
I just used it for my personal bot
yeah?
2022-03-16T06:38:49.473976+00:00 app[worker.1]: Traceback (most recent call last):
2022-03-16T06:38:49.473994+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/nextcord/ext/commands/core.py", line 168, in wrapped
2022-03-16T06:38:49.473994+00:00 app[worker.1]: ret = await coro(*args, **kwargs)
2022-03-16T06:38:49.474003+00:00 app[worker.1]: File "/app/main.py", line 506, in gcreate
2022-03-16T06:38:49.474004+00:00 app[worker.1]: users = await gaw_msg.reactions[0].users().flatten()
2022-03-16T06:38:49.474025+00:00 app[worker.1]: IndexError: list index out of range
2022-03-16T06:38:49.474038+00:00 app[worker.1]:
gaw_msg = await ctx.send(embed=embed)
await gaw_msg.add_reaction("🎉")
await asyncio.sleep(gaw_time)
new_gaw_msg = await ctx.channel.fetch_message(gaw_msg.id)
users = await gaw_msg.reactions[0].users().flatten()
Probably just some random kid running a hosting service on his gaming pc that his parents bought
who me?
I mean, what a sweat to break for making a register and login webpage ¯_(ツ)_/¯
guys?
Read your error
the message doesn't have any reactions
it had 3
ikr
asyncio.sleep 😔
😔
??

you are checking the original message fren, check the fetched message
kek
hmm isee
@cosmic agate copied code?
I mean, dont use sleep for long periods of time
True
I use asyncio.sleep for a mute command
I use time.sleep for a mute command
inferiority crisis
I have a mute command that timeouts a person even though the discord client offers an in-built timeout command just to make the commands look greater in number
😔
How to make Discord bot on python IDLE?
Haven't made Discord Bots since months now 
Uhhh?
what the-
code it
Yes but how to import Discord module?
import discord
\🙂
same uh, discord bots suck
More of, there ain't any good ideas anymore
discord bots are just too boring
Is there a way to check if a member is in cache?
Is the help command stored in cache? I'm thinking of making a func for my website which fills in my help command based on the results of the help command in the bot, saves me writing out by hand and needing to update it each time something changes
Guild.get_member will get you a member object if it's in Cache, else it would be None
and for the help command thing , consider making a dynamic help command using commands.HelpCommand instead of manually creating it
And implementation something similar in your web
yes but how to run
yeah that's my plan, I'm just wondering id it does API calls for that info or if it's stored in cache?
help command is nothing related to the API , so it's not an API call
what about slash commands? since they get registered with discord
run the file in command prompt ```py
python main.py
so could I write a check like this?py try: Guild.get_member(member) except None: Guild.fetch_member(member)
Okey thanks you 
yes (fetch is a coroutine)
im getting this in my bot's repl
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.```
or you could do ```py
member = guild.get_member(...) or await guild.fetch_member(...)
Thats just a warning
ye but why is it?
well read the warning
i didnt understand what that means ;/
Ik the difference but can't explain well enough so I hope this helps https://stackoverflow.com/questions/51025893/flask-at-first-run-do-not-use-the-development-server-in-a-production-environmen
ok thanks
how do u get authors guild icon
authors icon or guild icon?
ctx.guild.icon.url if ur using 2.0 or forks icon_url if ur using dpy 1.7.3
!d discord.Guild.icon
property icon```
Returns the guild’s icon asset, if available.
i see
icon_url seems to return an asset tough
i have a small design question.
ctx.respond.success("No problems")
ctx.success("No problems")
ctx.respond("No problems", "success")
ctx.respond("No problems", Color.SUCCESS)
in all examples success solely defines embed color. what is a better approach?
Do remember that authors could not have a guild attribute because it returned a User object instead.
how do i get the channel where the msg was edited using the event:
async def on_message_edit(msg)
Last one def.
mm
oh yeah.. but how do i get the channel
Think about a user DM
example: msg was edited in {channel}
before.channel
so for on_message_delete(msg), ig its just msg.channel?
It's ```py
async def on_message_edit(before, after)
also how do i get the modlogs channel id from this?
async def get_logs_channel(self, guild_id, channel_id):
data = self.bot.db.execute("SELECT channel_id FROM modlogs WHERE guild_id=$1, channel_id=$2", guild_id, channel_id)
author can be a Member or a User
!d discord.Message.author
depending on your library, the Bot class has methods which provide the slash commands registered for the current instance
there's literally one private bot for every server which dont even work nowadays, just to look cool
Ikr 
Discord Bot Maker do be earning a fortune
same
But the difference is that I offer a wide range of time vs the built-in 
Do u offer ∞?

I was making a bot but got invalid syntax what have i done wrong
for i in range(amount):
rand = random.randint(1, 2)
print(rand)
print("A")
if rand == 1:
print("fourtune")
whatugot.append(random.choice(pickaxes)
pickaxesadd += 1
if rand == 2:
whatugot.append(random.choice(fourtunes)
fourtunesadd += 1
print(whatugot)
You're missing a parenthesis at append
ohhhhh
at both appends
ty
👀
Use elif instead of if when checking rand's value the second time.
Also, indentation is weird in the second if block
How do I make a handler for BotMissingPermissions in try except /
//nextcord
how do i get person who banned and who got banned names/avatars using on_member_ban?
How do I send a message to a member
member.send
Tysm
You can query the audit log.
member.avatar?
it takes in guild and user
Idk
When that event fires you can see who got banned and iterate through audit log entires until you see the latest banentry for that user and break
thats for the user who got banned. what about the person who banned them
Ohh, ctx.author
this doesnt take in ctx
sad
!d discord.on_member_ban
discord.on_member_ban(guild, user)```
Called when user gets banned from a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This requires [`Intents.bans`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.bans "discord.Intents.bans") to be enabled.
Oh actually nvm then. You can’t by doing that.
i ended up doing
class ResponseType:
SUCCESS = Color.green
WARNING = Color.yellow
ERROR = Color.red
class Context(DPYContext):
async def respond(self, text: str, status: ResponseType):
response = Embed(color=status, description=text)
await self.reply(embed=response)
If It was my case I would use
@client.command()
async def ban(ctx, member : discord.Member, *, reason=None):
await member.send(f"You have been banned in {ctx.guild.name} for {reason}")
await member.ban(reason=reason)
await ctx.send(f"{member.mention} has been banned by {ctx.author.mention} for {reason}")```
so what about getting timestamp of that?
no no this is ban command.. im saying about loggings
Oh..
😔 I will just go away
Wa happen
Eh, someone has used yr name a bit too much with me that I have started to hate that word 🤣
Yeah... I just did some trolling?
Reee
Ofc
uhh
I cannot change my name
I don't hate him/her or smth, I don't even know them hahaha
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
I was going to play Apex anyways ¯_(ツ)_/¯
user.mention dosent mention user and sends phat error
What's the phat error
Traceback (most recent call last):
File "C:\Users\hustl\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\slash_core.py", line 597, in invoke
await call_param_func(self.callback, inter, self.cog, **kwargs)
File "C:\Users\hustl\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\params.py", line 778, in call_param_func
return await maybe_coroutine(safe_call, function, **kwargs)
File "C:\Users\hustl\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\utils.py", line 561, in maybe_coroutine
return await value
File "D:/Discord BOT/main.py", line 18, in slap
await ctx.send(f'{ctx.author.mention} slaps {user.mention}!')
AttributeError: 'str' object has no attribute 'mention'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\hustl\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\interaction_bot_base.py", line 1332, in process_application_commands
await app_command.invoke(interaction)
File "C:\Users\hustl\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\slash_core.py", line 606, in invoke
raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'mention'```
typehint user to discord.Member
Did you typehint user?
Or did you just
as in user: discord.Member
also rename your user argument to member because it's confusing otherwise since discord.User exists
Is that a question
yes
File "D:/Discord BOT/main.py", line 17, in <module>
async def slap(ctx, user: discord.Member):
File "C:\Users\hustl\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\interaction_bot_base.py", line 491, in decorator
result = slash_command(
File "C:\Users\hustl\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\slash_core.py", line 677, in decorator
return InvokableSlashCommand(
File "C:\Users\hustl\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\slash_core.py", line 367, in __init__
options = expand_params(self)
File "C:\Users\hustl\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\params.py", line 787, in expand_params
_, inter_param, params, injections = collect_params(command.callback)
File "C:\Users\hustl\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\params.py", line 699, in collect_params
paraminfo = ParamInfo.from_param(parameter, {}, doc)
File "C:\Users\hustl\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\params.py", line 385, in from_param
self.parse_annotation(type_hints.get(param.name, param.annotation))
File "C:\Users\hustl\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\params.py", line 529, in parse_annotation
raise TypeError(f"{annotation!r} is not a valid parameter annotation")
TypeError: <class 'discord.member.Member'> is not a valid parameter annotation```
Did you do member: discord.member.Member?
discord.Member exists too lol .-. class with capital letter and variable all lower-case, that's how our father told us
What did you typehint it as
? that's what I'm saying lmao
rename your argument from user to member since otherwise it's confusing
File "D:/Discord BOT/main.py", line 17, in <module>
async def slap(ctx, member: discord.Member):
File "C:\Users\hustl\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\interaction_bot_base.py", line 491, in decorator
result = slash_command(
File "C:\Users\hustl\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\slash_core.py", line 677, in decorator
return InvokableSlashCommand(
File "C:\Users\hustl\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\slash_core.py", line 367, in __init__
options = expand_params(self)
File "C:\Users\hustl\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\params.py", line 787, in expand_params
_, inter_param, params, injections = collect_params(command.callback)
File "C:\Users\hustl\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\params.py", line 699, in collect_params
paraminfo = ParamInfo.from_param(parameter, {}, doc)
File "C:\Users\hustl\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\params.py", line 385, in from_param
self.parse_annotation(type_hints.get(param.name, param.annotation))
File "C:\Users\hustl\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\params.py", line 529, in parse_annotation
raise TypeError(f"{annotation!r} is not a valid parameter annotation")
TypeError: <class 'discord.member.Member'> is not a valid parameter annotation```
thats it type hinted
no need
Im asking him if he did that
bruh why discord.member.Member, just discord.Member
How do I make my bot detect if the user is a bot
The typehint is visible in the error
discord.Member is fine as dpy has an initiate file for name spaces
!d discord.User.bot
Yeah it's only discord.Member
Specifies if the user is a bot account.
And it's not discord.member.Member
ok
so can i be helped?
Bro what
t
Didnt help
\🗿
We did help you
but it just gave me an error
You aren't reading
🗿
all I read was rguments
🗿
arguments about discord.member.Member
It's disnake.Member
... code
thanks
hey
Sup
show the full error
it can't find the package, compare your project with the one you imported in the vds
An exception has occurred while executing command `mine`:
Traceback (most recent call last):
File "C:\Users\turne.DESKTOP-8B1DN4C\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_slash\client.py", line 1353, in invoke_command
await func.invoke(ctx, **args)
File "C:\Users\turne.DESKTOP-8B1DN4C\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_slash\model.py", line 210, in invoke
return await self.func(*args, **kwargs)
File "C:\Users\turne.DESKTOP-8B1DN4C\OneDrive\Desktop\Dogeminer\main.py", line 89, in mine
with open('storage.json', 'w') as f:
TypeError: 'BaseCommandObject' object is not callable
if chance_for_rock <= chance_radius:
users[str(ctx.author.id)]["rocksmined"] += 1
rocksmined += 1
with open('storage.json', 'w') as f:
json.dump(users, f)
eh
Hey guys my bot just passed 75 servers and I got pm to verify but am facing this error
How to overcome it?Where should I insert the link?
Yea Ik but I mean where should I put the link?
Its asking me to put the link somewhere
See in the pic I sent
Its saying you are missing invite link....
Nvm man I guess you aint getting what its trying to convey
Umm how can I add that?
An exception has occurred while executing command `mine`:
Traceback (most recent call last):
File "C:\Users\turne.DESKTOP-8B1DN4C\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_slash\client.py", line 1353, in invoke_command
await func.invoke(ctx, **args)
File "C:\Users\turne.DESKTOP-8B1DN4C\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_slash\model.py", line 210, in invoke
return await self.func(*args, **kwargs)
File "C:\Users\turne.DESKTOP-8B1DN4C\OneDrive\Desktop\Dogeminer\main.py", line 89, in mine
with open('storage.json', 'w') as f:
TypeError: 'BaseCommandObject' object is not callable
``` how do i fix this?
dme me @inner epoch i got a vid for u
Aye for sure
No I never had any bot invite link ever
I just shared the link by creating from oauth and from there people invited
can someone help me???
wha u need m8
```An exception has occurred while executing command mine:
Traceback (most recent call last):
File "C:\Users\turne.DESKTOP-8B1DN4C\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_slash\client.py", line 1353, in invoke_command
await func.invoke(ctx, **args)
File "C:\Users\turne.DESKTOP-8B1DN4C\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_slash\model.py", line 210, in invoke
return await self.func(*args, **kwargs)
File "C:\Users\turne.DESKTOP-8B1DN4C\OneDrive\Desktop\Dogeminer\main.py", line 89, in mine
with open('storage.json', 'w') as f:
TypeError: 'BaseCommandObject' object is not callable
hmm
It worked before
what if i want to input something in this format
hi
it doesnt work and just gives the text
just put the same way u do
hm
``
Does anyone know???
Could you show us your code?
its in a password generator and the special characters sometimes make it italics so i tried to append "``" to either side but it gives this
#;##@@,.(@s.;(,@.#(h:&%$%>-;_+^<(#u(%!,h>-p<i@&%#i$.,;:<;^=+(,o$^<i>%^.#$.^)!>+#&>=^<,!.#$3&.%.&>::>b^^
!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.
oh wait the text bbroke
if chance_for_rock <= chance_radius:
users[str(ctx.author.id)]["rocksmined"] += 1
rocksmined += 1
embed = discord.Embed(description=f"{ctx.author.mention} Mined!",color=0xf8fd08)
embed.set_thumbnail(url="https://upload.wikimedia.org/wikipedia/en/d/d0/Dogecoin_Logo.png")
embed.add_field(name="Amount :", value=f"{money}Ɖ" , inline=True)
with open('storage.json', 'w') as f:
json.dump(users, f)
if chance_for_rock <= chance_radius:
embed.add_field(name=f"Dude, you mined a rock! You now have {rocksmined}:rock:", value="⠀", inline=False)
await ctx.send(embed=embed)
else:
embed = discord.Embed(description=f"Oops, cooldown! you need to wait {round(cooldown - time.perf_counter(), 2)} Seconds! WOW")
embed.set_thumbnail(url="https://upload.wikimedia.org/wikipedia/en/d/d0/Dogecoin_Logo.png")
await ctx.send(embed=embed)
hm
this is how im adding it
@swift monolithis that a bot?
How do I make a handler for BotMissingPermissions in try except /
//nextcord
yes it is in a bot code
i helped him out
when sending in dms it doesnt put in that formatting
ohhh i forgot to remove it thanks
anyone know why this is not working??



