#discord-bots
1 messages Β· Page 279 of 1
so discord.py or pycord
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
cant use two at once
alr thanks i'll look into that
I dont know what i did wrong, but it says "unexpected indent" on the last line of code
@client.command()
async def help(ctx):
embed = discord.Embed(title="List of commands for this bot!")
embed.add_field(name="$help - this command!", value="Show this message.", inline=False)
embed.add_field(name="$show, $showpic - google images search!", value="Search for any image in Google!", inline=False)
embed.add_field(name="$snsfw - \U0001F51E", value="Same as $show, but with SafeSearch off... Works only in NSFW channels, though!", inline=False)
embed.add_field(name="$fox", value="Random fox!", inline=False)
embed.add_field(name="$meme", value="Random meme from r/memes!", inline=True)
embed.add_field(name="$ping", value="Pong!", inline=True)
await ctx.send(embed=embed)
!e
def a():
b = 0
b+1
return b
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | File "/home/main.py", line 4
002 | return b
003 | IndentationError: unexpected indent
there's a lot of potential causes for a hanging program, but asyncio doesnt normally take a long time cancelling asynchronous tasks - do you have any code that involves threads? those can very easily hang programs indefinitely
anyone knows why my imports are white ? they are normally like greenish
everything is white all of a sudden
It's your linter not an error
Change it back to the one you were previously using
That will revert the changes to the colors
when creating Bot instance pass help=None
let me try..
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
help_command
help_command
monocraft font π΅βπ«
yes i like it
Wouldn't the help command throw an error?
As there are two help commands so isn't that command already exist
If they made the command using on_message, no
I see
Why would anyone want to change their background anyway
idk
I'll stick to my dark theme
Dusk theme top
Instead of custom bg and all that
also tell which package are u using
if its discord.py then it isn't a correct syntax
fix the intentation
What do you mean it isn't a correct syntax
huh?
Attribute and syntax errors are not the same
I meant that's not how its done
you should be my teacher
damn Why am I paying for internet
jk

I love cats too

so ig he will be fine teacher for me
noo all cats are mine
Anyways I had some funny question actually related to disnake
But uh I broke its internals (second time already) and I no longer have it

Problem was it called on_timeout after actually stopping view but I use callback-less views and that caused code to get executed anyway
So had to overwrite _dispatch_timeout function
Yall should try callback-less components fr
you called .stop but it Timed out anyways?
well I'll try
Nah it timed out, but library first stops, then calls on_timeout, but I needed it to be done in reverse order
Why though
Lemme show
We have uh this piece of code
for hero in heroes:
embed.add_field(hero.name, hero.get_stats())
await inter.send("Select your hero!", view=view, embed=embed)
hero, inter = await view.get_result(inter, ResponseMode.EDIT)
view = BossFightView(inter, hero, boss := get_random_boss())
await view.start()
bobux_bal = 0
while True:
await view.wait()
if view.timed_out:
await inter.send(
embed=FailEmbed(
inter.user,
"Bruh your hero fell asleep and got all earned bobux stolen. "
f"Please don't go away next time. Thank your **{hero.name}** they didn't leave you",
)
)
break
elif not view.hero_won:
Sorry for bad indents
The thing is on_timeout set the timed_out attribute but since it stopped before, wait() actually exited before that attribute was set
Sure take a look at these classes I made
https://github.com/Exenifix/disnake-bot-template-postgres/blob/master/utils/views.py
I was gonna sleep actually but I think should take a look once
this is an interesting manner since people usually when using views move logic from command to the views and handle it there but ur receiving bare minimum results from view and handling it in commands
atleast i handle complex logic as view extension in view itself
altho i like ur method in case of modals and views combined
I don't like callbacks implementation because you split code which is like unified whole, putting some part into callbacks splits it for no reason and makes it difficult to navigate, although in some cases callbacks method is obviously better
mhm
That's why we're using genericviews in bobux everywhere 
Remember the BadModal
man i need to learn typing features but dunno how and where
Learn any statically typed language
i know already c# or typescript but in python its not built in meaning its different
It's different in syntax but not in concept
and it has many classes i dont get like Type or any else like when im supposed to use it
Just imagine python as statically typed
yeah concept i get
What I used so far were only function typehints and generics
Guess function typehints is too broad
function typehint easy
You mean the typing module?
yeah
Well you positioned your sentence like you necessary need to use every single class from there
Which is probably not true
Cause you need only what you need
yeah sorry could sound like that
https://github.com/Skurczybyki/bot/blob/main/src/env.py
this is first time me using Generics
What I'm trying to say is you don't need to know what everything in typing does, but when you need to do something just learn about it
Asher prolly now finding out i copied his code and modified it xd
yeah i know that but i dont really know what i need thats the problem
schools trying hard not to use this method in education
src/env.py line 17
cast: t.Type[T] = MISSING```
this im actually curious if this is correct way of typehinting that
typecheckers dont say antyhing
Well so basically when you provide something to cast, T gets the type of that something and remembers it for instance. And when you use for example __get__ which returns T, it means it will return type of what the T was set to
Regarding that env thing I actually made a module π€
!pypi exenenv
hm but if i provide cast=int then what it typehints cast to
it typehints it to type of int?
nice
What you are probably missing is concept of metaclasses or "class of class"
!E print(type(int))
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
<class 'type'>
Yeah this is the metaclass
When you typehint something as
a: MyClass
You expect a to be set to instance of that class
a: MyClass = MyClass()
But when you typehint it with Type
a: Type[MyClass]
You expect it to be class itself
a: Type[MyClass] = MyClass
when you access it its invoked i belive
Ah so that's getattr
!d typing.TypeVar
class typing.TypeVar(name, *constraints, bound=None, covariant=False, contravariant=False)```
Type variable.
Usage:
```py
T = TypeVar('T') # Can be anything
S = TypeVar('S', bound=str) # Can be any subtype of str
A = TypeVar('A', str, bytes) # Must be exactly str or bytes
``` Type variables exist primarily for the benefit of static type checkers. They serve as the parameters for generic types as well as for generic function and type alias definitions. See [`Generic`](https://docs.python.org/3/library/typing.html#typing.Generic "typing.Generic") for more information on generic types. Generic functions work as follows:
sadly you cant set default value for generic
i could set default value of cast to str
someone told me its comming in python 3.12
Ah yes that makes more sense
But surely #type-hinting folks know the way for it
i asked how they would improve it
how can I check if a slash command is used in a dm?
check if guild is None
if interaction.guild.id == None:
can I check if the id is None
yes but why not just guild
no just guild
oh
if interaction.guild is None
oh ok
discord/ext/commands/core.py lines 2306 to 2311
def predicate(ctx: Context[BotT]) -> bool:
if ctx.guild is not None:
raise PrivateMessageOnly()
return True
return check(predicate)```
so not the id
thats how the dm_only check works
I'm using discord.py, anybody know why message.attachments is yielding an empty list even though there's an image attached to the message?
!d discord.Message.attachments
A list of attachments given to a message. If Intents.message_content is not enabled this will always be an empty list unless the bot is mentioned or the message is a direct message.
do you have message_content intent enabled?
ah shit a new intent
!paste
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
how would i make a command that makes multiple emojis at once? the emojis wouldnt be picked or anything it would be emojis i put in the code, so the emojis would always be the same ones
why doesn't my app show up on this page after authorizing?
it once worked but now it doesn't
I removed it to test it with diffrent scopes but now it just won't show even with the same scopes
that means its not currently Authorized
iirc discord oauth has time limit set on tokens on which u have to refresh and re authorise ur application but that time limit is relatively large
this modifies the view of the sent response, how do i modify the current view after a response message is sent?
await interaction.response.send_message(
content='Confirm',
view=ConfirmButton(),
ephemeral=True
)
await interaction.edit_original_response(view=None)
@ me if you can help
whats
you cant
there is not emoji format
π
like nerdbot
so that feature in the tool is pretty much useless
we're not going to help you abuse stolen accounts here.
alright mate calm down
what does that emoji mean
they're my accounts they aren't stolen
byeah nerdbot reacts with random nerd emojis but you can use this to make a poll feature maby a timer, giveaways ANYTHING
my only experience is with webhooks and i can code bdfd
Yo @slate swan may i get help?
So this keeps saying the x1 value is greater than x0 and i just dont get why it gives me the error ```def create_level_card_image(username, level, xp):
bg_image = Image.open("Pokemon.png")
bg_image = bg_image.resize((400, 200))
width, height = bg_image.size
img = Image.new("RGBA", (width, height), (255, 255, 255, 0))
img.paste(bg_image, (0, 0))
font = ImageFont.truetype("arial.ttf", 24)
draw = ImageDraw.Draw(img)
draw.text((30, 30), f"{username}'s Level", font=font, fill=(0, 0, 0, 255))
draw.text((30, 70), f"Level: {level}", font=font, fill=(0, 0, 0, 255))
draw.text((30, 100), f"XP: {xp}/100", font=font, fill=(0, 0, 0, 255))
xp_percent = xp / 100
progress_width = min(int(200 * xp_percent), 200)
draw.rectangle([30, 140, 30 + progress_width, 160], fill=(0, 255, 0, 255))
draw.rectangle([30 + progress_width, 140, 230, 160], fill=(255, 0, 0, 255))
return img```
Theres the code tryna code a lvl system
@buoyant quail U wanna help mabey? hehe
heres the error btw ```Traceback (most recent call last):
File "C:\Users.BELUGHA\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users.BELUGHA\Downloads\Discord Bot\Luffy0102.py", line 309, in xp
img = create_level_card_image(user.display_name, level, xp)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users.BELUGHA\Downloads\Discord Bot\Luffy0102.py", line 280, in create_level_card_image
draw.rectangle([30, 140, 30 + progress_width, 160], fill=(0, 255, 0, 255))
File "C:\Users.BELUGHA\AppData\Local\Programs\Python\Python311\Lib\site-packages\PIL\ImageDraw.py", line 294, in rectangle
self.draw.draw_rectangle(xy, fill, 1)
ValueError: x1 must be greater than or equal to x0
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users.BELUGHA\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users.BELUGHA\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users.BELUGHA\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: x1 must be greater than or equal to x0```
@elfin island Wanna help me mabey? heh
anyone wanna help me?
Have patience and just wait
Damns XD mb
Do you wanna help me mabey? heheπ
no idea but the error is not really related to discord bots itself
it comes from PIL so try asking in #1035199133436354600
Oh damn alr thanks!

How do i print a users server nickname... the update seems to have changed it..
!d discord.Member.nick
The guild specific nickname of the user. Takes precedence over the global name.
Thanks
hllo there im making my first ever discord bot, i just want to know how to even start coding it since im restarting it from scratch.
is this how i start the bot up to begin with?
import discord
import os
from discord.ext import commands
from keep_online import keepy_uppy
intents = discord.Intents.default()
intents.typing = False
intents.presences = False
bot = commands.Bot(command_prefix="&&", intents=intents)
keepy_uppy()
bot.run(os.environ['TOKEN'])
im hosting on replit btw
and the TOKEN is my actual bot token
yeah should be ok
sick
but wont you need intents?
now how di i add commands?
wdym?
slash or normal?
what is the bot for?
election bot, i dont really know how to explain it beyond that
which one is more flexable?
is it just commands really?
i want to make it send private messages to the person who send the command and have reactions they can choose to enter certain categories and chose a person to vote for
Message commands are generally more flexible, as you can make your own parser. But slash commands have the benefit of choices and autocompletes
hmmm
ok
yeah id go with / since its more memorable and has that pop up with a description
intents.message_content = True
intents.members = True
``` add this and turn on message content intents and member intents in discord developer
A hands-on guide to Discord.py
so the bot can read messages and do what?
A guide you can see some examples and explaination but its not fully done yet
well you want to message users privately
so the member intents is needed
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
the first rule says it should be >3.9, does replit use that python ver?
You dont need members intent to send messages to users
I don't know about you, but sending DMs don't require member intents
oh.
discord.py also support 3.8
i dont mean sending dms
Do python --version and find out
you mean what then?
nvm i should be using dms since it makes things easier and whatnot
ephemeral?
pardon?
no im changig it to dms
sorry for the confusion
I have this code and it keeps telling me that,
TypeError: function() argument 'code' must be code, not str```
The Python Code is:
```py
import os, sys
import random, string, math, decimal
import re, struct
import uuid, hashlib, base64
import threading as thr
import _thread as thread
import asyncio, timeit, time
import socket, select, selectors, pickle
import csv, json
import numpy as np
import discord
from discord.ext import tasks, commands
from discord.utils import get
from discord import Intents
with open("bot.json", "r") as f:
BOT = json.load(f)
token = BOT["token"]
intents = Intents.default()
intents.members = True
intents.presences = True
intents.guild_messages = True
bot = commands.Bot(command_prefix='$', intents=intents)
@bot.event
async def on_ready():
print("{0} Online".format(bot.user.name))
if __name__ == "__main__":
bot.run(token)
Full traceback?
Traceback (most recent call last):
File "C:\Users~\OneDrive\Desktop\Arcane\arcane.py", line 12, in <module>
import discord
File "C:\Users~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord_init_.py", line 23, in <module>
from .client import *
File "C:\Users~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 49, in <module>
import aiohttp
File "C:\Users~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\aiohttp_init_.py", line 6, in <module>
from .client import (
File "C:\Users~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\aiohttp\client.py", line 35, in <module>
from . import hdrs, http, payload
File "C:\Users~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\aiohttp\http.py", line 7, in <module>
from .http_parser import (
File "C:\Users~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\aiohttp\http_parser.py", line 15, in <module>
from .helpers import NO_EXTENSIONS, BaseTimerContext
File "C:\Users~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\aiohttp\helpers.py", line 667, in <module>
class CeilTimeout(async_timeout.timeout):
TypeError: function() argument 'code' must be code, not str
im on 3.10!
Are you running up to date discord.py
yes
What version you have
2.2.3
do pip install -U discord.py
thks it works, guess it was just out of date
Yep
how can i check my discord version on my shell??
pip show discord.py
thx
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f'We have logged in as {bot.user}')
@bot.command()
async def kick(ctx, member: discord.Member, *, reason=None):
await member.kick(reason=reason)
await ctx.send(f'{member.mention} has been kicked.')
bot.run('TOKEN')
Why the command doesn't work?
The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."
The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.
Privileged intents, such as message content, have to be explicitly enabled from the Discord Developer Portal in addition to being enabled in the code:
intents = discord.Intents.default() # create a default Intents instance
intents.message_content = True # enable message content intents
bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor
For more information on intents, see /tag intents. If prefix commands are still not working, see /tag on-message-event.
i want to make a discord bot with slash commands how to i do it in discord.py version 2.3.1
!mcintent
but i want to runn it as a bot not client
So subclass a Bot
is there a way i can make my bot go offline when a command is run via discord?
!d discord.Client.close
await close()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Closes the connection to Discord.
is there a way for me to turn off my bot then turn it on again?
bascially a restart
what's you intentions behind doing so? Refreshing code for commands?
yeah?
Where we can hire people?
!d discord.ext.commands.Cog use cogs
class discord.ext.commands.Cog(*args, **kwargs)```
The base class that all cogs must inherit from.
A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the [Cogs](https://discordpy.readthedocs.io/en/latest/ext/commands/cogs.html#ext-commands-cogs) page.
When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta") are equally valid here.
With extensions
This allows you to hot reload your commands without restarting the bot
!d discord.ext.commands.Bot.reload_extension
await reload_extension(name, *, package=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Atomically reloads an extension.
This replaces the extension with the same extension, only refreshed. This is equivalent to a [`unload_extension()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.unload_extension "discord.ext.commands.Bot.unload_extension") followed by a [`load_extension()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.load_extension "discord.ext.commands.Bot.load_extension") except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state.
so this is my code:
async def create_ticket(self, interaction: discord.Interaction):
global ticket_count
# Check if the ticket count has reached the limit (50)
if ticket_count >= 2:
await interaction.followup.send("Sorry, the ticket limit has been reached. Please try again later.", ephemeral=True)
return```
and i am getting the following errror:
https://srcb.in/ym7MLuBRKr
and the message "Sorry, the ticket limit has been reached. Please try again later." is not being sent
Can someone dm me to code me a bot robotmoney_with_wingsmoney_with_wings
Due to rule 9 we cant
!rule 9
We can for free
Yeah we also dont code for people but we help them solve their problems with code
Which library are you using?
Version?
version 1.7.3
Update then
thanks worked
hey, need some help with an unban command for a slash bot..
ok
whats your problem
it doesnt work...
instead of doing all the for loop stuff you could just do this
typehint user_id as int
then just do await interaction.guild.unban(discord.Object(id=user_id))
because you don't need the full user object to ban, just the id
Hey there. Im new to programming. Is anyone here, that has knowledge about SQL-Injection? Wanted to ask a few small things in dm ^^ (pymongo + discordpy)
Mongodb isn't vulnerable to SQL injections since it's a nosql database
!sql-fstrings
Don't use f-strings (f"") or other forms of "string interpolation" (%, +, .format) to inject data into a SQL query. It is an endless source of bugs and syntax errors. Additionally, in user-facing applications, it presents a major security risk via SQL injection.
Your database library should support "query parameters". A query parameter is a placeholder that you put in the SQL query. When the query is executed, you provide data to the database library, and the library inserts the data into the query for you, safely.
For example, the sqlite3 package supports using ? as a placeholder:
query = "SELECT * FROM stocks WHERE symbol = ?;"
params = ("RHAT",)
db.execute(query, params)
Note: Different database libraries support different placeholder styles, e.g. %s and $1. Consult your library's documentation for details.
See Also
β’ Python sqlite3 docs - How to use placeholders to bind values in SQL queries
β’ PEP-249 - A specification of how database libraries in Python should work
The error explained itself
async generator can't be awaited
!d discord.Guild.bans
async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry").
You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") to get this information.
Changed in version 2.0: Due to a breaking change in Discordβs API, this now returns a paginated iterator instead of a list.
Examples
Usage...
There's an example in the docs
oh okay thanks alot. Yea I see. I import it with MongoClient. Only use it so users can add youtube links to my database (collection.insert_one({"link": cliptoadd}))
Only check if it is a youtube link. Maybe I add regex later on
yep you can use regex for that
but doesn't youtube have different formats(domains) for redirects like
youtube.com
youtu.be ,
yt.be etc etc
yep thats why i have to do it with regex later on. Found this https://regex101.com/r/vHEc61/1
!paste
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
@bot.tree.command(name="purge", description="Purge messages in a channel")
async def purge(ctx: discord.Interaction, amount: int):
await ctx.channel.purge(limit=(amount + 1))
embed = discord.Embed(title="Purge Results", color=rnp_color, timestamp=datetime.now(), description=f"""
Sucessfully purge `{amount}` messages.
""")
time = datetime.now().strftime("%c")
embed2 = discord.Embed(title="Purge")
embed2.add_field(name="Executor", value=f"`{ctx.user.display_name}`")
embed2.add_field(name="Purge Amount", value=f"`{amount}`", inline=False)
embed2.set_footer(text=time)
await ctx.response.send_message(embed=embed)
await log_channel.send(embed=embed2)```
sorry sending error, i had to delete paste i accidentally sent bot token
You purge, so you delete the interaction, so the bot cannot send a response to a deleted interaction
Defer the interaction π€·
your right
when i do channel.send instead it does this
even though it worked
so how can i respond if the interaction is being deleted
log_channel = bot.get_channel(1136515581550530710) also it says that is a NoneType and doesnt have method .send
this didnt work...same error
why ctx, should be interaction right
when i make it int, it says enter a valid integer even though i put in a valid user id
ints cant start with 0
so what do i change?
keep that in mind
so this is my code:
async def create_ticket(self, interaction: discord.Interaction):
global ticket_count
# Check if the ticket count has reached the limit (50)
if ticket_count >= 2:
await interaction.followup.send("Sorry, the ticket limit has been reached. Please try again later.", ephemeral=True)
return```
and i am getting the following errror:
https://srcb.in/ym7MLuBRKr
and the message "Sorry, the ticket limit has been reached. Please try again later." is not being sent
someone told me:
looks like you didn't respond first
you have to responded before you can send followups```
can someone tell what did he meant by respond before followups?
@wispy pasture Do py return await interaction.followup.send("Sorry, the ticket limit has been reached. Please try again later.", ephemeral=True)
oooo okay
could i get some help here please :)
nope... something else is the issue
i couldnt find it
Show your entire code
That message was meant for this
Find what
the example youre mentioning
why's it print
!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if itβs within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
It means exactly what it means, limit how many ban entries will be yielded
im sorry, i dont understand what you mean by yielded
means u will get
?
Show your full code
why does my app only shows up on my authorized apps when the url looks like this :
https://discord.com/api/oauth2/authorize?client_id=xxxxxxxxxxxxx&redirect_uri=https%3A%2F%2Fwww.example.com&response_type=token&scope=identify guilds.join
and not like this?
https://discord.com/api/oauth2/authorize?client_id=xxxxxxxxxxxxx&redirect_uri=https%3A%2F%2Fwww.example.com&response_type=code&scope=identify guilds.join
the difference is in the type parameter
I think think it is something with the time limit bc now I tried it with the type=code right after I tried with type=token and the token worked but the code not...
Can someone tell me how to make a code that sends an embed with a Button UI and when I press that button it sends a modal after i completed the modal it sends an embed with another ui and when I press it sends another modal
UI buttons
thats exactly what im after lmao
You too
you can use interaction.response.send_message and supply it with a new view that contains the buttons you want, its been a while since i did this so i could be missing a detail
When I'm trying to get info on an embed, if its sidebar color is set to discord.Colour.default() or has otherwise a value of 0, the result I get from quering Embed.color is None. All other values return fine. My issue is that values of None and 0 when you sent an embed are 2 different colors and only having None as a return value makes you unable to distinguish between the two
i feel that is intended or is a bug
run_bot Is my main function and im using asyncio.get_event_loop().create_task(run_bot()).
Now the bot seems to work but I get thefollowing message in the terminal. :
- RuntimeWarning: coroutine 'run_bot' was never awaited self._ready.clear()
How do I await this?
pls share the core and the full error
task: <Task pending name='Task-1' coro=<run_bot() running at D:\dc bot\prayer_times.py:97>>
C:\Users...\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py:671: RuntimeWarning: coroutine 'run_bot' was never awaited
self._ready.clear()
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
@app_commands.command(name="user")
async def user(self, interaction:discord.Interaction, user: discord.Member):
Userdiscord = await self.bot.fetch_user(user.id)
"""Gets info on a member, such as their ID."""
embed = discord.Embed(title=user.name, colour=user.colour)
embed.set_image(url = Userdiscord.banner)
embed.add_field(name="Name:", value=user.name)
embed.add_field(name="ID:", value=user.id)
embed.add_field(name="Status:", value=user.status)
embed.add_field(name="Highest role:", value=user.top_role)
embed.add_field(name="Joined:", value=user.joined_at)
embed.set_thumbnail(url=user.avatar)
await interaction.response.send_message(embed=embed)
How do I make this slash command only show to admin and not all members
create a logic for that
All information in the embed are already all publicly available to everyone 
hru teacher 
just [bumping](#discord-bots message) in case anyone can share some insight
how to make a dicord py bot with slash commannd annd runn it like a bot not client
@app_commands.command(name = "confess", description = "Confess something")
async def confess(self, Interaction:discord.Interaction, confession:str):
await Interaction.response.send_message("Confession sent", hidden = True)
anyone know how I can make the response only visible to the person who did the slash command?
@copper gulch is that a slash command
discord API simply doesn't give you that data for 0 and None
yea
you can check this by seeing the API response [when you fetch], both of them results in no color field given for their embeds
its a slash command
like a bot or a cliet??
client**
and @copper gulch can you send me the code to make a slash command
thanks for the reply
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
so anyone know?
thx
!d discord.InteractionResponse.send_message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
ephemeral (bool) β Indicates if the message should only be visible to the user who started the interaction. If a view is sent with an ephemeral message and it has no timeout set then the timeout is set to 15 minutes.
thank you
how to run this
import discord
from discord import app_commands
from discord.ext import commands
class MyCog(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
@app_commands.command(name="command-1")
async def my_command(self, interaction: discord.Interaction) -> None:
""" /command-1 """
await interaction.response.send_message("Hello from command 1!", ephemeral=True)
@app_commands.command(name="command-2")
@app_commands.guilds(discord.Object(id=...), ...)
async def my_private_command(self, interaction: discord.Interaction) -> None:
""" /command-2 """
await interaction.response.send_message("Hello from private command!", ephemeral=True)
async def setup(bot: commands.Bot) -> None:
await bot.add_cog(MyCog(bot))
It's an extension
You don't run it, you load it
how
For example put that code into myextension.py file, then in your main do this
class MyBot(commands.Bot):
def __init__(self):
super().__init__(...) # whatever you put in constructor
async def setup_hook(self):
await self.load_extension("myextension") # here we load it
bot = MyBot()
bot.run(...)
Also will need to sync the commands but idk how to do that in dpy
is there a way to make it all i onnnne file
Probably self.tree.sync() in setup_hook
Why'd you need it to
Extensions are recommended way of organising dpy bots
ik
You can ofc, just copy functions and change decorators
okay thanks
embed33.set_footer(text=f'Type "/confess" to send a confession')
await channel.send(embed=embed33)
anyone know how I can add timestamp here with UTC+08?
!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if itβs within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
pass timestamp ^
import asyncio
import discord
from discord.ext import commands, app_commands
intents = discord.Intents.default() # Default intents
intents.typing = False
intents.presences = False
bot = commands.Bot(command_prefix="!", intents=intents)
@bot.command()
async def my_command(ctx: commands.Context):
await ctx.send("Hello from my command!")
@bot.group(name="some-parent", description="description")
async def group(ctx: commands.Context):
if ctx.invoked_subcommand is None:
await ctx.send("Invalid subcommand.")
@group.command()
async def my_subcommand(ctx: commands.Context):
await ctx.send("Hello from the subcommand!")
bot.add_command(group)
async def main():
# Set up your commands here
bot.remove_command("help") # Optional, if you want to remove the default help command
async with bot:
await bot.start("MT...Xs")
if __name__ == "__main__":
asyncio.run(main())
i get
python3 main.py
Traceback (most recent call last):
File "/home/***/Documents/Code/******/FlareMod/main.py", line 3, in <module>
from discord.ext import commands, app_commands
ImportError: cannot import name 'app_commands' from 'discord.ext' (unknown location)
ahhh thank you
its discord.app_commands
but how can I add it in the footer of an embed?
So i do
import discord.app_commads
from discord import app_commands
okay thx
A hands-on guide to Discord.py
i got this
python3 main.py
Traceback (most recent call last):
File "/home/****/Documents/Code/******/FlareMod/main.py", line 25, in <module>
bot.add_command(group)
File "/home/****/.local/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 246, in add_command
super().add_command(command)
File "/home/****/.local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1356, in add_command
raise CommandRegistrationError(command.name)
discord.ext.commands.errors.CommandRegistrationError: The command some-parent is already an existing command or alias.
you already defined command with such name
import asyncio
import discord
from discord import app_commands
from discord.ext import commands
intents = discord.Intents.default() # Default intents
intents.typing = False
intents.presences = False
bot = commands.Bot(command_prefix="!", intents=intents)
@bot.command()
async def my_command(ctx: commands.Context):
await ctx.send("Hello from my command!")
@bot.group(name="some-parent", description="description")
async def group(ctx: commands.Context):
if ctx.invoked_subcommand is None:
await ctx.send("Invalid subcommand.")
@group.command()
async def my_subcommand(ctx: commands.Context):
await ctx.send("Hello from the subcommand!")
bot.add_command(group)
async def main():
# Set up your commands here
bot.remove_command("help") # Optional, if you want to remove the default help command
async with bot:
await bot.start("MT...Xs")
if __name__ == "__main__":
asyncio.run(main())
why you do bot.add_command(group) when the @bot.group(name="some-parent", description="description") decorator already adds the command
i coped it for a gist
well its not correct
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
so what should i do
i dont see anywhere the bot.add_command(group) line
also this gist is for slash commands and you only have prefixed ones
so how to i make a discord bot that has a supported slash command
you do what this gist actually tells you what to do or read examples on discord.py github https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/basic.py
so use bot
okay thannks
anyone know a faster way of finding what channel a user last messaged in without looping through all channels?
maybe cache the channel id's when a user sends a message
yeah this idea worked really well tysm
glad it helped. Not sure how you decided to implement it but I like using cachetools https://cachetools.readthedocs.io/en/latest/
so this is my code:
async def create_ticket(self, interaction: discord.Interaction):
global ticket_count
# Check if the ticket count has reached the limit (50)
if ticket_count >= 2:
await interaction.followup.send("Sorry, the ticket limit has been reached. Please try again later.", ephemeral=True)
return```
and i am getting the following errror:
https://srcb.in/ym7MLuBRKr
and the message "Sorry, the ticket limit has been reached. Please try again later." is not being sent
and i am using no webhook
when I defer my slash commands my error handler doesnt send the embed
@tree.error
async def on_app_command_error(interaction: discord.Interaction, error: AppCommandError):
await interaction.response.defer()
command = interaction.command.name
channel2 = client.get_channel(1112053260879147130)
if isinstance(error, app_commands.CommandOnCooldown):
await interaction.followup.send(error, ephemeral=True)
else:
button = Button(label="support server", url="url")
view = View()
view.add_item(button)
embed = discord.Embed(title="An error has occured", description="If you need help with this error join the support server.", colour=discord.Colour.red)
await interaction.followup.send(embed=embed, view=view)
await channel2.send(f"{command} command used by {interaction.user} but an error occured")
traceback.print_exc(limit=None, file=None, chain=True)
if you didnt defer the interaction you dont use followup
when you see global you know its bad
really?? i was taught that :/\
yeah that could be the issue ngl
i would recomment avoid using global
also followup is a Webhook so you are in fact using one
but yeah you can followup when you defer interaction
wait what now followup is webhook?
always have been?
!d discord.Interaction.followup
Returns the follow up webhook for follow up interactions.
anyone know?
interesting, i never knew
can you show the command that you are using to trigger this
theres a few but ill just show you one
@client.tree.command(name="kick", description="kicks a user (moderator only)")
@app_commands.default_permissions(kick_members=True)
async def kick(interaction: discord.Interaction, member: discord.Member, *, reason: str = "no reason provided"):
await interaction.response.defer()
try:
embed = discord.Embed(title=f"{member} was kicked by {interaction.user}", color=discord.Color.blue())
embed.add_field(name= "Reason:", value = f"{reason}")
await member.kick()
await interaction.followup.send(f"{member} was kicked.")
log = r.get(f"logs:{interaction.guild.id}")
log2 = int(log.decode("utf-8"))
logging = client.get_channel(log2) or await client.fetch_channel(log2)
await logging.send(embed=embed)
await member.send(f"you were kicked from ``{interaction.guild.name}`` reason: {reason}")
except KeyError:
pass```
so I think the issue is that you are defering the same interaction twice
yeah why defer it inside error handler too
hey! for some reason, when i do /unban on a user, the ban still exists...how can i fix that?
oh ok
command runs through the bot and i get the embed (has been unbanned), but the ban is still in list of bans
!d discord.Guild.unban
await unban(user, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Unbans a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") to do this.
it accepts Snowflake
so you dont have to loop over all bans
you can just pass discord.Object(id=int(user_id))
Traceback (most recent call last):
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/tree.py", line 1089, in wrapper
await self._call(interaction)
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/tree.py", line 1252, in _call
await self.on_error(interaction, e)
File "/Users/zagzag/vscode/zagzag/zagzag.py", line 1087, in on_app_command_error
embed = discord.Embed(title="An error has occured", description="If you need help with this error join the support server. ", colour=discord.Colour.red)
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/embeds.py", line 179, in __init__
self.colour = colour if colour is not None else color
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/embeds.py", line 323, in colour
raise TypeError(f'Expected discord.Colour, int, or None but received {value.__class__.__name__} instead.')
TypeError: Expected discord.Colour, int, or None but received method instead.
where though
to the unban method
Colour.red is a class method you need to call it
!d discord.Object
class discord.Object(id, *, type=...)```
Represents a generic Discord object.
The purpose of this class is to allow you to create βminiatureβ versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.
There are also some cases where some websocket events are received in [strange order](https://github.com/Rapptz/discord.py/issues/21) and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.
x == y Checks if two objects are equal.
x != y Checks if two objects are not equal.
hash(x) Returns the objectβs hash.
it needs to be an id?
i did int but when i put it on the test it says need valid integer
even though its an valid id
show what you tried?
you did it already here: py embed = discord.Embed(title=f"{member} was kicked by {interaction.user}", color=discord.Color.blue())
@bot.tree.command(name="unban", description="Unban a user from the server")
@commands.has_permissions(ban_members=True)
async def unban(interaction: discord.Interaction, user_id: int):
# Fetch the banned users using async for loop
banned_users = interaction.guild.bans()
async for entry in banned_users:
if entry.user.id == int(user_id):
interaction.guild.unban(entry.user)
embed = discord.Embed(title="User Unbanned", description=f"{entry.user.mention} has been unbanned.", color=0x40caf7)
await interaction.response.send_message(embed=embed)
return```
ah ok
and where is the part i told you to do?
cause you changed nothing
yeah, do you want me to put that in the async for?
Traceback (most recent call last):
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/tree.py", line 1089, in wrapper
await self._call(interaction)
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/tree.py", line 1252, in _call
await self.on_error(interaction, e)
File "/Users/zagzag/vscode/zagzag/zagzag.py", line 1088, in on_app_command_error
await interaction.response.send_message(embed=embed, view=view)
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/interactions.py", line 772, in send_message
raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before```
so you dont have to loop over all bans
no you dont use the loop
await interaction.response.send_message(embed=embed, view=view)```
you already responded before to that interaction so this needs to be a followup
dont you have to because the command is a coroutine?
without the defer?
in the error handler
you defered it in the command
ok
the error handler just recieves that interaction
π
what
you need to have "async for" in unbans right?
why?
thanks
you cant use async generator for unban command
i have no idea why you want that for loop so bad
.
my guess is as some attempt at a weird way to error handle a user not being found in the bans
try/except
it raises NotFound
so you're saying i can remove the async for part?
yeah like 4th time
just do guild.unban
and pass discord.Object inside
with the id being user_id passed to command
even the discord obj?
@bot.tree.command(name="unban", description="Unban a user from the server")
@commands.has_permissions(ban_members=True)
async def unban(interaction: discord.Interaction, user_id: str):
discord.Object(id=int(user_id))
interaction.guild.unban(user_id)
embed = discord.Embed(title="User Unbanned", description=f"{user_id.mention} has been unbanned.", color=0x40caf7)
await interaction.response.send_message(embed=embed)
return
you can keep user_id as an int
you also need to await unbanning someone
and you dont need that discord.Object line
await the guild unban line?
yup
π
and you also should resync your commands
still says i need a valid integer
did you resync
yea
how sure are you π
can you show the full error and update your code again
and the code again?
@commands.has_permissions(ban_members=True)
async def unban(interaction: discord.Interaction, user_id: int):
await interaction.guild.unban(user_id)
embed = discord.Embed(title="User Unbanned", description=f"{user_id.mention} has been unbanned.", color=0x40caf7)
await interaction.response.send_message(embed=embed)
return```
await fetch_user(user_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.
Note
This method is an API call. If you have [`discord.Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_user()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.get_user "discord.Client.get_user") instead.
Changed in version 2.0: `user_id` parameter is now positional-only.
also like suggested before you can go back to using discord.Object
In the method
π
you can fetch the user or construct your own object but you need to pass that to the unban method
So should I put the line right after the discord.object which id put after the async def?
not sure i understand your question but you can just do await interaction.guild.unban(discord.Object(id=user_id)))
And Iβd put this where
well its one or the other
I see, just need one?
you either make the object yourself with what i just sent or you fetch the user from the api
@bot.tree.command(name="purge", description="Purge messages in a channel")
async def purge(ctx: discord.Interaction, amount: int):
await ctx.channel.purge(limit=(amount + 1))
embed = discord.Embed(title="Purge Results", color=rnp_color, timestamp=datetime.now(), description=f"""
Sucessfully purge `{amount}` messages.
""")
time = datetime.now().strftime("%c")
embed2 = discord.Embed(title="Purge")
embed2.add_field(name="Executor", value=f"`{ctx.user.display_name}`")
embed2.add_field(name="Purge Amount", value=f"`{amount}`", inline=False)
embed2.set_footer(text=time)
await ctx.channel.send(embed=embed)
await bot.get_channel(1136515581550530710).send(embed2)```
How can i delay the interaction so i can respond to it
because if you dont respond it says interaction failed
!d discord.InteractionResponse.defer
You never actually respond to interaction
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
how long does it defer for
i wanna say like 15 minutes but i would have to look it up
i want like 3 seconds
You never actually respond to interaction telling once again
its a purge command
ctx.channel.send() sends a message, not responds
You need ctx.response.send_message()
And better call instance of Interaction interaction or inter
Until you respond, max time is 10 minutes iirc
so how could i make it respond like in 3 seconds
also i prefer calling the interaction ctx
its 15
so how could i get it to respond 3 seconds after
defer response ----> followup
@bot.tree.command(name="purge", description="Purge messages in a channel")
async def purge(ctx: discord.Interaction, amount: int):
await ctx.response.defer(ephemeral=False,thinking=False)
await ctx.channel.purge(limit=(amount + 1))
embed = discord.Embed(title="Purge Results", color=rnp_color, timestamp=datetime.now(), description=f"""
Sucessfully purge `{amount}` messages.
""")
time = datetime.now().strftime("%c")
embed2 = discord.Embed(title="Purge")
embed2.add_field(name="Executor", value=f"`{ctx.user.display_name}`")
embed2.add_field(name="Purge Amount", value=f"`{amount}`", inline=False)
embed2.set_footer(text=time)
await ctx.response.send_message(embed=embed)
await bot.get_channel(1136515581550530710).send(embed2)```
also the laste line wont work it saying NoneType has no attribute send
you have to followup
wdym followup
ctx.followup.send_message
ty
Discord.py is bad
weird
await fetch_channel(channel_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel"), [`abc.PrivateChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.PrivateChannel "discord.abc.PrivateChannel"), or [`Thread`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Thread "discord.Thread") with the specified ID.
Note
This method is an API call. For general usage, consider [`get_channel()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_channel "discord.ext.commands.Bot.get_channel") instead.
New in version 1.2.
Changed in version 2.0: `channel_id` parameter is now positional-only.
Try this
there is a channel with that id tho
Yeah might not be in bot's cache
and ive been using the bot.get_channel method for all my bots
A getch function would be much safer.
Too bad dpy doesn't have it
I mean you can make it pretty easily.
Can make it yourself tho not a big deal
async def getch_channel(self, id: int):
return self.get_channel(id) or await self.fetch_channel(id)
Yeah
@vale wing wat
Wat
Advising to add the getch_channel to your bot subclass tho
File "/home/runner/RNP-Discord-Bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 828, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 130, in purge
await ctx.followup.send_message(embed=embed)
AttributeError: 'Webhook' object has no attribute 'send_message'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/RNP-Discord-Bot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/RNP-Discord-Bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/RNP-Discord-Bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: AttributeError: 'Webhook' object has no attribute 'send_message'```
its send
Since when channel_id a kwarg
async def purge(ctx: discord.Interaction, amount: int):
await ctx.response.defer(ephemeral=False,thinking=False)
await ctx.channel.purge(limit=(amount + 1))
embed = discord.Embed(title="Purge Results", color=rnp_color, timestamp=datetime.now(), description=f"""
Sucessfully purge `{amount}` messages.
""")
time = datetime.now().strftime("%c")
embed2 = discord.Embed(title="Purge")
embed2.add_field(name="Executor", value=f"`{ctx.user.display_name}`")
embed2.add_field(name="Purge Amount", value=f"`{amount}`", inline=False)
embed2.set_footer(text=time)
await ctx.followup.send_message(embed=embed)
log = await bot.fetch_channel(channel_id=1136515581550530710)
log.send(embed=embed)```
https://github.com/PokeDis/PokeLore/blob/master/src/core/bot.py#L171-L179
Always wondered if that can work
Delete discord.py and install disnake
no
Oh frick I didn't look at that
Oh its private
Leak the lines
@staticmethod
async def getch_data(extension: "BaseExtension", category: str, query: str | int) -> T: # type: ignore
get_query = getattr(extension, f"get_{category}")
fetch_query = getattr(extension, f"fetch_{category}")
try:
data = get_query(query) or await fetch_query(query)
except ResourceNotFound as e:
raise PokeLanceInvalidQuery(e)
return data
Sorry for indent π΅βπ«
yay new error
Return type T..? Lazy
!paste
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
Im not the one who made it
error ^^^
async def purge(ctx: discord.Interaction, amount: int):
await ctx.response.defer(ephemeral=False,thinking=False)
await ctx.channel.purge(limit=(amount + 1))
embed = discord.Embed(title="Purge Results", color=rnp_color, timestamp=datetime.now(), description=f"""
Sucessfully purged `{amount}` message(s).
""")
time = datetime.now().strftime("%c")
embed2 = discord.Embed(title="Purge")
embed2.add_field(name="Executor", value=f"`{ctx.user.display_name}`")
embed2.add_field(name="Purge Amount", value=f"`{amount}`", inline=False)
embed2.set_footer(text=time)
await ctx.followup.send(embed=embed)
log = await bot.fetch_channel(channel_id=1136515581550530710)
log.send(embed=embed)```
T = t.TypeVar("T", bound=BaseModel) πΏ
You create a slash command but you send a message command?
So yeah first of all
ctx.followup.send(...)
Sorry I just genuinely hate discord.py I can't provide proper help on it
Second, if you do add that method it's just
channel = await bot.getch_channel(...)
If you don't it's
channel = bot.get_channel(id) or await bot.fetch_channel(id)
if channel is None:
print("Failed to fetch log channel")
return
await channel.send(...)
Nah that should be illegal.
@cloud dawn hoW iS bOBuX DynAmiC uPDatE sySTeM/!?/12
π³
@slate swan uh oh I just opened your gh and got jumpscared
I will get to it this week I promise, you have permission to mention annoy me.
Bot we are working on
await ctx.followup.send(embed=embed)```
I'm not taking any credit for the bot base
Quite uh we
says unknown error
What error exactly
async def purge(ctx: discord.Interaction, amount: int):
await ctx.response.defer(ephemeral=False,thinking=False)
await ctx.channel.purge(limit=(amount + 1))
embed = discord.Embed(title="Purge Results", color=rnp_color, timestamp=datetime.now(), description=f"""
Sucessfully purged `{amount}` message(s).
""")
time = datetime.now().strftime("%c")
embed2 = discord.Embed(title="Purge")
embed2.add_field(name="Executor", value=f"`{ctx.user.display_name}`")
embed2.add_field(name="Purge Amount", value=f"`{amount}`", inline=False)
embed2.set_footer(text=time)
await ctx.followup.send(embed=embed)
log = await bot.get_channel(1136515581550530710) or await bot.fetch_channel(1136515581550530710)
if log == None:
print("Failed to fetch log channel")
return
log.send(embed=embed)```
Ive made other commands before why is purge so stingy
== None 
null
I forgot if java has is operator tho
Maybe you need to set thinking to True?
Hate discord.py
I literally know everyone πΏ
https://paste.pythondiscord.com/F5LA
Gotta love errors
Can invite you if you wish
the error is in the followup.send
Your followup saying fu
someone help
Doesn't mean it's not caused by deferring
So try that
Can webhooks send empty messages?
try what?
!d discord.InteractionResponse.defer
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
okay we are making progress
its purging, but its not sending the logging embed
File "/home/runner/RNP-Discord-Bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 828, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 131, in purge
log = await bot.get_channel(1136515581550530710) or await bot.fetch_channel(1136515581550530710)
TypeError: object TextChannel can't be used in 'await' expression
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/RNP-Discord-Bot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/RNP-Discord-Bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/RNP-Discord-Bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 842, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: TypeError: object TextChannel can't be used in 'await' expression```
Because you don't need first await
@vale wing ill think about joining what the bot does though
get_channel is sync
oopsie
discord.com/application-directory/841991913258745876 well can see by yourself
.bm
Will check out when on pc
Sure


same error, even after the change
This cant be int since its too big for int limit
oh...
Just pass a user object
i thought there was no max int limit?
There is :l
It's like 32 bit or smth
i thought it was just the memory limit
Yeah but I forgor the int naming
there isnt in py3 i thought
Any integer between -2^53 and 2^53
Yeah basicly this ^
We're talking about the API
is that not well within the id length?
Nope
!e print(2**53)
@cloud dawn :white_check_mark: Your 3.11 eval job has completed with return code 0.
9007199254740992
2^53 is 16 digits, IDs now reach 19 digits
!e print(1057126299623243797 < 2**53)
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
False
should i go w str?
Yep but may I ask, why a unban command?
interesting
unban users xd
But the server has a ui for unbanning them..
ik but its easier for moderation
Unless you make a whole moderation system with automated user history logging.
Try discord.Object annotation
would await member.send work if the user is not in the server
Member object is per guild basis so you cant have a Member object if the member is not inside guild
unless you meant User then it would work
no cause you can only kick member
ok
User represents a global Discord user and a GuildMember represents a Discord user on a specific server
you can kick someone from a guild so it must be per guild Member
so how can I turn a user object into a member Object
in a command
then annotate it as Member
no like I want the User object to turn into a Member Object when kicking a member but then turn back to a User object to send them a dm
well then you can try using .send on member object
since he was in guild when you gathered the object
as annotation to the arg?
no how you wanna put it in decorator
annotation to the command function param
user_id: discord.Object
meant async derf
my varible for the discord.Member Object is member. To check if the member is a bot can I do If member.bot:
!d discord.Member.bot
property bot```
Equivalent to [`User.bot`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.bot "discord.User.bot")
so its correct?

π
how can I check if the dms is off?
try sending message and check for errors
I have a try and except thing
that will do

if i wanted to get the ID members robux clothign games and games visit how would i get all those values?
right now the embed is in a embed object
Can someone tell me why when I turn the bot on and I press my UI button it works but after a few minutes it doesn't and if i turn it off then back off it's working again
My code - https://paste.pythondiscord.com/7AQA
how would i enable all intents except message content and presence intent?
is it just discord.Intents.members?
enable all and disable the ones you want
how
!d discord.Intents.all
classmethod all()```
A factory method that creates a [`Intents`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents "discord.Intents") with everything enabled.
intents = discord.Intents.all()
intents.something = False
intents.other_intent = False
oh bet
thanks forgot you can do that
if i dont got the message content intent i cant have custom prefixes right
correct
they're not that bad though!
Then move to hybrid commands
Probably won't need a lot of code changes besides the decorators
Just generate a custom id at that point
We hate readability
nextcord doesnt support that
and i wont switch to another library for sure
?
nextcord 
btw what is wrong here?
In options.1.options.0.name: Command name is invalid
@join.subcommand(description="Join kick")
@commands.guild_only()
@commands.cooldown(1, 2, BucketType.user)
@commands.has_permissions(kick_members=True)
async def kick(self, ctx, Toggle: int = nextcord.SlashOption(choices={"on": 1, "off": 2}, required=False)):
bro
i had that since the start β οΈ
im not playing i love nextcord too
really
i use it in my projects too
oh nice
Disnake 
any1?
Can't have spaces in slash cmds
you cant have a command named super commadn unless its a sub command
ah thats what you mean
You literally named your command Join kick
but its a sub command
Sounds like john wick
its the description
Name parent command join and child kick
yes
Don't name your child john wick ok
i will
just John is fine
nah ima name him john dick
there are many John's
That's what a John would say
show how you define join
@nextcord.slash_command(guild_ids=[1103819860993118318])
@commands.guild_only()
@commands.cooldown(1, 2, BucketType.user)
@commands.has_permissions(manage_channels=True)
async def join(self, ctx):
@command(name="john")
async def parent(...):
...
@parent.sub_comnand(name="wick")
async def josh_weam(...):
...
.sub_comnand 
i just started migrating to slash commands
Disnake moment don't mind
its so weird
@slate swan you saw project details I sent you?
oh yeah i did sorry i did not respond
I am very annoying project manager
Can confirm
ill text you soon
can anyone help me now im confused
Well I tried but you seemed to ignore that?
WHAT
Same, I think I'm just gonna go to sleep. Confusion will still be there tomorrow.
im very confused now
Don't include parent command name into child
where is it included
Right here first line
but it needs to be like this
Source?
Right? So weird that people put their parets or uncles name on a childs middle name.
i mean it says it there
Well guess nextcord docs are fricked up
oh my god
Ikr here in Russia we don't do that
We have patronymics
Well their parent command is main and children are called Subcommand n and yeah those are invalid names as well as they contain spaces
That's why it's fricked up
Instead your alphabet looks like china and north korean had a baby together.
Guys, do you know of any free hosts out there that I can use to host my bot? Idc if it's bad, anything will do
@sick coyote listen just change the name of child command to kick I promise it will work
If it won't I will give you all my bobux
AWS has free stuff, Azure has some stuff for students and your very last resort would be heroku.
That's weirdest russian alphabet origin version I ever seen ngl
Thanks π
im very confused with this parent and child shit
Engaging spoonfeeding
my main language is not english
what a great domain
yeah right very long
Is slave master less confusing?

Basically to the top command owns the lower command
@command(name="master")
async def master(...):
...
@master.subcommand(name="slave")
async def slave(...):
...
Then your command will be /master slave
@command(name="white")
async def parent(...):
...
@parent.sub_comnand(name="black")
async def josh_weam(...):
...
Yeah same stuff
A Python wrapper for the Discord API forked from discord.py - nextcord/nextcord
@vale wing have to get that first warning in 3 years.
i want to call my main command tho
Haha yes
Report yourself
"racist code"
lol sometimes I do think I near the very edge. But I do like it there.
well you cant really
it still doesnt work wow
I watched the movie django and I do feel more racist, in a good way tough.
banned from?
If there was no dollar sign I'd even fax it to him.

He's not even in the server anymore.
@slate swan
Oh he is

I reported him alr
hi lemon juice
oh i didnt even notice i got an offer too
gotcha
maybe cuz i got 7 message requests already
didn't read the rules
i shall leave peacefully, thanks guys
have a good one
π
what you use for metrics?
giving up is worse than failing
im not happy with my bot
and i dont feel like migrating and stuff like that it takes too long
Own methods 
Bobux was in the same situation but with the power of friendship we rewrote it to slash commands in a few months
few motnths????
i thought i could make it in 2 hours
The bot was quite big
how much commands does it have
Yeah
in how much servers is it
Why not run it when we have such curves
oooo
Currently in 268
nice
just only 200 testing servers
β οΈ
Tbh many of them are fr bot and one person
But those persons ain't my alts istg
the problem for my bot is it got custom prefix and i cant just sit down and take my time
without the slash commands my bot is unusable
Migrating from text cmds to slash right?
exactly
Yeah that's painful
very
im thinking about just completely coding a new bot for 1 specific module




