#discord-bots
1 messages Β· Page 197 of 1
having a user-local installation is generally more convenient since you wont need to deal with privilege escalation, e.g. when installing packages
true, but depend on the context also
in the context of someone installing python to write their own programs, thats the case
anyway, is everything working now?
admin cmd -> pip install discord.py
Access through python
type "python" in terminal and show screenshot
π
I think I got what's going on, you have installed python for local user in the first place then installed it for everyone
but the default launch is probably set for the local user wich don't have the pypi config
go to control pannel then uninstall everything python related and do a clean install
??
there should be python launcher and your version
letme show you
theses 2
uninstall them
thats what i did every time
oof
uninstalled the launcher too
this is weird
AttributeError: 'InteractionResponse' object has no attribute 'followup'
Read
shit
Traceback (most recent call last):
File "C:\Users\Xmich\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "c:\Users\Xmich\OneDrive\Desktop\New folder\Website\main.py", line 66, in select_callback
await interaction.followup(view=view)
TypeError: 'Webhook' object is not callable
!d discord.Webhook.send - followup returns a webhook, read the docs
await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message using the webhook.
The content must be a type that can convert to a string through `str(content)`.
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.
If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") and it must be a rich embed type. You cannot mix the `embed` parameter with the `embeds` parameter, which must be 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 to send.
Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.11)") instead of `InvalidArgument`.
Can I include text with my send_message for example something like this
interaction.response.send_message("Do this", view=view, ephemeral=True)
heβs on a windows computer pip will not work
I've been using pip and windows for 5 years now
it does work
the way you have it worded will not work
hence why it says the word βpipβ is not recognized as a command
add pip to path and it's all good
iβve had pip to path and even if i did try it the way you worded it, it wouldnβt work
!d discord.InteractionResponse.send_message - content kwarg
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.
again hence why it is unrecognized as a command
maybe it's a bad config in your end, probably antivirus or just weird path settings
parental control maybe? π
or non admin user
because you didn't add pip to path
β¦
how do i take a list of users in an app command
whats the best discord bot library to use?
I want one that has slash commands and forms
How do I create a channel under a specific category
A bunch of arguments
Or modal
could i have an example?
Slash commands are not good at this in general
@ionic garden maybe you could make it take in a string then you take in the user id and split it for each space?
or split for each \n
yeah but ngl that seems kinda scuffed
It won't have that though
idk then
Disnake is easiest but its modals impl kinda sucks. You can do own one tho
Don't use command argument, instead attach user select in response
could i have an example for possibly how to do that?
!d discord.ui.UserSelect
class discord.ui.UserSelect(*, custom_id=..., placeholder=None, min_values=1, max_values=1, disabled=False, row=None)```
Represents a UI select menu with a list of predefined options with the current members of the guild.
If this is sent a private message, it will only allow the user to select the client or themselves. Every selected option in a private message will resolve to a [`discord.User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").
New in version 2.1.
can it do pretty much anything I'd need it to do tho?
idk what u mean by modals impl sucks sorry im new to this type of thing
Everything you can do with dpy you can do with disnake
Except you might not be able to do manual sync but who needs it after all
Modals are "forms" as you call them
How do I create a channel under a specific category
!d discord.Guild.create_text_channel
await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., default_auto_archive_duration=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") for the guild.
Note that you must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") to create the channel.
The `overwrites` parameter can be used to create a βsecretβ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.
Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
category kwarg
in a view, can i show diff buttons to diff users?
no
that's an f
Make one button, when user presses it bot sends an ephemeral with individual buttons that they can interact with
i have a mysql db
should i store discord uids as bigints or strings, or is it a matter of preference
Technically itβs more optimized to use bigints
But I highly doubt that would be an issue for you
Which one occupies more bytes, a string or a bigint?
bigint should take less memory
String typically takes more yeah
Bigint should take 64 bits which means 8 bytes, string takes a byte per character in UTF-8 iirc
yeah
Anyone know how to make a slash command guild only in disnake?
Disnake?
disnake kinda weird ngl
put up a guild deco or just disable the dm feature
!d disnake.ext.commands.guild_only
@disnake.ext.commands.guild_only()```
A [`check()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.check "disnake.ext.commands.check") that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command.
This check raises a special exception, [`NoPrivateMessage`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.NoPrivateMessage "disnake.ext.commands.NoPrivateMessage") that is inherited from [`CheckFailure`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.CheckFailure "disnake.ext.commands.CheckFailure").
It's for normal prefix cmd, try finding slsh cmds deco too
Tho as far as i know the decos are same with commands and slash command in disnake
What's so weird about it
just use d.py
bigger community, more reliable, etc.
I know both libs and still I prefer disnake
I have stated its pros and cons somewhere
My question was about your opinion to it
I dont know disnake in general but some other forkd like pycord
most of them still uee the old app cmd syntx
their code is inefficient
...
Hm?
You mean one where all parameters had to be described in decorator?
yes you prb wouldnt call it syntax would you?
bruuuuh
Imagine not having different types of interactions
imagine needing multiple type of interactions
they were introduced to simplify things and to achieve a better design but ig you don't understand them at all π¦
no need simplify something already that simple
Monin' 
sup
!d discord.ext.commands.guild_only
@discord.ext.commands.guild_only()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command.
This check raises a special exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
If used on hybrid commands, this will be equivalent to the [`discord.app_commands.guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only "discord.app_commands.guild_only") decorator. In an unsupported context, such as a subcommand, this will still fallback to applying the check.
guys
is it possible to make a event that does something when a member RECEIVES a role?
like i mean the member is for like 1 hour on the server now and when i give him a role something runs?
on_member_update i suppose
ok, thanks
btw hi
ty
Can discord bot Hey how it going is it possible to take data from google sheets and paste then click ok?
what games?
Overwatch rn
Hi some one have an example to send msg from python code to nextcord chatbot?
Hey, I'm trying to create a slash command using py-cord 2.4.0
If I follow the documentation's provided code:
import discord
bot = discord.Bot()
@bot.event
async def on_ready():
print(f"We have logged in as {bot.user}")
@bot.slash_command(guild_ids=[your, guild_ids, here])
async def hello(ctx):
await ctx.respond("Hello!")
bot.run("your token here")
I get this error:
module 'discord' has no attribute 'Bot'
File "D:\Projects\LeagueNebula_Bot\utils.py", line 18, in <module>
bot = discord.Bot()
File "D:\Projects\LeagueNebula_Bot\main.py", line 1, in <module>
from utils import *
AttributeError: module 'discord' has no attribute 'Bot'```
Can someone explain why, and how I can solve this?
Just for clarification, the bot is multifile. definitions n stuff are in utils, but they're imported into main. So that shouldn't be the problem
uninstall other libraries with discord namespace and reinstall py-cord
yes, i have already done that
no.
!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.
he;s using pycord not discord.py, its has discord.Bot
oh mb then
The following section outlines the API of Pycordβs prefixed command extension module. Bots: Bot: Attributes activity, allowed_mentions, application_flags, application_id, cached_messages, case_inse...
._.
the docs doesn't say the same
@slate swan
there's both, check again
which is the name of yor file?
send full code
if I use commands.Bot I must use command_prefix which is what im trying to avoid
!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.
which ide / code editor are you using?
vscode
#importing libraries
import discord
from discord.ext import commands
import os
import sqlite3
GUILDS = [ "1075018380064596021", #Bot Playground
"1073753136558256179", #League Nebula
]
bot = commands.Bot()
con = sqlite3.connect("LeagueNebula.db")
cur = con.cursor()
ctrl + left click on import discord
from utils import *
@bot.event
async def on_ready():
print("Bot is online.")
await bot.change_presence(status=discord.Status.online, activity=discord.Game("Hi there!"))
#cogs here
#####################################################
# TEST COMMAND #
#####################################################
@bot.slash_command(description="first slash command", guild_ids=GUILDS)
async def test(ctx):
await ctx.send("Succes!")
bot.run(os.environ.get("TOKEN"))
I am just confused on your organisation
why
makes sense to me
utils should be available everywhere
main is the file that starts the bot
send THE WHOLE file
it's a folder!
!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.
try to use everything in the same file and see what it happes
the same issue persists
which I don't find very surprising as nothing really changes
ctrl + right click
ik
try left click then
yeye
ignore voting.py it is empty
it does indeed not contain discord.Bot
it does have Client, but that isn't compatible with "slash_command"
here's the whole init file
Im not sure about the folder its in. I will have a look when I get home.
It could be discord.py hasn't uninstalled fully
I force deleted it
Installed pycord again
And now import discord cant be resolved
do you need help?
or are u just sharing the code
just sharing π
pretty
thank you
i try to make hybrid meme command but for some reason its spamming for no specific reason
@client.hybrid_command()
async def memes(ctx):
reddit = praw.Reddit(
client_id = "id",
client_secret = "your-secret",
user_agent = "put-any-name",
check_for_async=False
)
subreddit = reddit.subreddit("memes")
all_subs = []
hot = subreddit.hot(limit=50)
for submission in hot:
all_subs.append(submission)
random_sub = random.choice(all_subs)
url = random_sub.url
em = discord.Embed(color=0xb8f3ff)
em.add_field(name="Have Some Memes", value="From r/memes", inline=False)
em.set_image(url = url)
await ctx.send(embed = em)
spamming what?
keep spamming random images
well you're fetching 50 submissions and sending all of them in your code
hot = subreddit.hot(limit=50)
for submission in hot:
not sure why you have that if you only want to send it once
TypeError: type 'Collection' is not subscriptable , basically its not reading from modules
from modules import bank_funcs, inventory_funcs
from config import Auth
modules name white , but everything is , modules folder and files in there but why not readig
it seems that this only allows one user to be selected?
Change max_values kwarg or how is it named in dpy
!d discord.ui.UserSelect
class discord.ui.UserSelect(*, custom_id=..., placeholder=None, min_values=1, max_values=1, disabled=False, row=None)```
Represents a UI select menu with a list of predefined options with the current members of the guild.
If this is sent a private message, it will only allow the user to select the client or themselves. Every selected option in a private message will resolve to a [`discord.User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").
New in version 2.1.
Yeah max_values
how do i do that
class UserInvite(discord.ui.View):
@discord.ui.select(cls=UserSelect, placeholder="Select a user please!")
async def my_user_select(self, i: discord.Interaction, select: UserSelect):
await i.response.defer()
```bc this is how i'm using it rn & i don't see a place to pass it in
@discord.ui.select(*, cls=<class 'discord.ui.select.Select'>, options=..., channel_types=..., placeholder=None, custom_id=..., min_values=1, max_values=1, disabled=False, row=None)```
A decorator that attaches a select menu to a component.
The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View"), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") you receive and the chosen select class.
To obtain the selected values inside the callback, you can use the `values` attribute of the chosen class in the callback. The list of values will depend on the type of select menu used. View the table below for more information.
There's max_values kwarg too
anyone can help me tho
Is there any easier way to fix this?
invite_message = None
try:
invite_message = await next_player.send(embed=invite_embed)
except discord.Forbidden:
pass
await asyncio.sleep(60)
if invite_message is not None:
await invite_message.delete()```
I'm getting Local variable 'invite_message' might be referenced before assignment without invite_message = None
if .send throws discord.Forbidden then invite_message will not be a variable
File "c:\eco\modules\bank_funcs.py", line 46, in DataBase
def cursor(self, table_name: str) -> Collection[Mapping[str, Any]]:
~~~~~~~~~~^^^^^^^^^^^^^^^^^^^
TypeError: type 'Collection' is not subscriptable
this doesn't give info pertaining to your error
@ionic gardenBut that error linking to this
def cursor(self, table_name: str) -> Collection[Mapping[str, Any]]:
return self.db[table_name]
where did you import Collection
mongo
just send your whole code
hm, don't have much experience w/ pymongo
but maybe it just isn't one of those subscriptable types like typing.List
how's that
add a from __future__ import annotations
at the very start of the module
same
dont understand at this moment :d
lack of brains atm
@vocal snowcan you explain more
please how to get the member avatar in on_member_join?
do you know what strings are
member.avatar.url not work
not work how?
how to get the member avatar in on_member_join?
@vocal snownot sure
.avatar or .display_avatar
no...
you haven't used strings in python?
dont work
how???
@vocal snowstill learning about everyting
are you getting an error or what
strings are a very basic concept
you should know this stuff first
anyways if you don't know about strings im not sure why you are typehinting your code... i guess you copied it from somewhere
i need get the url...
so .avatar / .display_avatar will return an Asset object
@commands.Cog.listener()
async def on_member_join(self, member):
channel= self.bot.get_channel (1074708154799116348)
userData = {
"name": f"{member.name}",
}
background = Editor(Canvas((900, 300), color="#242424"))
profile_picture = await load_image_async(member.display_avatar)
profile = Editor(profile_picture).resize((150, 150)).rounded_corners(radius=20)
!d discord.Member.display_avatar
property display_avatar```
Returns the memberβs display avatar.
For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.
New in version 2.0.
and then you can use .url on that
if i use member.avatar.url it dont work, i have a traceback with this
.avatar and .display_avatar are different things
No
Ahhhh glitch
Was trying to reply to the Lancebot message the same time it deleted, lol
lancebot needs to change prefix π
Traceback (most recent call last):
File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "e:\SSD\Python\Code\Projets\DevBot\DiscordBot\cogcmd\welcome.py", line 21, in on_member_join
profile_picture = await load_image_async(member.avatar.url)
AttributeError: 'NoneType' object has no attribute 'url'
@vocal snow
so member.avatar is None
they didn't set a custom avatar
its a test profile...
^^ so u can use this instead
please claim a help channel #βο½how-to-get-help
i need to create a if, with if the member has no avatar > display server avatar?
or can i pass this step?
you can see in the docs it will always return Asset
@vocal snowCan you explain me how to use string in this situation ?
put quotes around the type
as shown here
!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.
@commands.Cog.listener()
async def on_member_join(self, member):
if member.avatar.url == None:
pass
channel= self.bot.get_channel (1074708154799116348)
userData = {
"name": f"{member.name}",
}
background = Editor(Canvas((900, 300), color="#242424"))
profile_picture = await load_image_async(member.avatar.url)
maybe you guys can understand it now:
https://paste.pythondiscord.com/raw/cokamuwaho
i did it , but same problem
that's unnecessary... just use member.display_avatar directly
you have to do that for each annotation
for some reason the function is not callled by compiler
depiste being called in theory
but im getting error and for this class DataBase:
which function?
oh right, got it working now
Traceback (most recent call last):
File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "e:\SSD\Python\Code\Projets\DevBot\DiscordBot\cogcmd\welcome.py", line 21, in on_member_join
profile_picture = await load_image_async(member.display_avatar)
File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\easy_pil\utils.py", line 56, in load_image_async
async with session.get(link) as response:
File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\client.py", line 1138, in __aenter__
self._resp = await self._coro
File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\client.py", line 422, in _request
url = self._build_url(str_or_url)
File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\client.py", line 356, in _build_url
url = URL(str_or_url)
File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\yarl\_url.py", line 154, in __new__
raise TypeError("Constructor parameter should be str")
TypeError: Constructor parameter should be str
you forgot the .url
since your function expects a string, not an Asset
sub_roll is a method of the class
you need to have a self parameter
where?
and a lot of your code is broken
you're using .append with more than 1 argument in many places
in roll_result
i was planning to use a matrix
being one part the roll result
and the other the total, at least on sub_roll
@vocal snowIf i want to edit shop, to buy not items but Roles, how supposed i do it ?
Ill do myself, and send it here if its right π
But wait, i need edit whole DB , its bad
if I have a datetime.datetime object, how would I utilize it to display a unix timestamp?
.timestamp()
and there is also the index storer followed by the operator storer
so for example you could do:
f"<t:{round(member.created_at.timestamp())}:F>"
thanks a lot for your help!
yw
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
there's also this for a bit of convenience
alright thanks!
i don't know what i need to fix
so Zeffo, why my roll is not working?
maybe you could help me on fixing on what is broken on my code
@slate swan what's this supposed to do
indice.append([cont,cont+1], indz)
first it's suppose to store the number indicies between the operator, like 0 and 1 for the first number. Then the indz store the operator, being it +, -, *, /. Storing both of them as metadata
is there a way to store it better, like store 2 instead of 1?
like meta data?
that's what i'm talking about
what you're doing is indices.append('something', 'something2')
yea
well u can't append 2 items at once
that should work
what's the error
it doesn't show, it just stop working and gives me the else output that the args are invalid. It didn't even enters the function
is there a debug code that allows me to show error message?
so i can show you something for you to help me?
do u have jishaku installed
Can someone help me? I'm trying to create a bot that looks for empty groups on a web page, but when I try it, the bot does nothing and gives me an error.
what's the error
in group_scanner
^^^^^^^^^^^^^^^^
proxy_auth, proxy_addr = next(proxy_iter)
proxy_auth, proxy_addr = next(proxy_iter)
File "C:\Users\Angel\OneDrive\Escritorio\h0nderobloxclaimablegroupfinder-main\core\threads\group_scanner.py", line 24, in group_scanner
proxy_auth, proxy_addr = next(proxy_iter)
proxy_auth, proxy_addr = next(proxy_iter)
StopIteration
StopIteration
^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^
proxy_auth, proxy_addr = next(proxy_iter)
StopIteration
StopIteration
^^^^^^^^^^^^^^^^
StopIteration
and it repeats like 20 times
can u elaborate what u mean by look for empty groups on a web page
Search between groups and if you see an empty one, send it to the discord
the complete error is here : https://pastebin.com/27VxzE8S
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.
where do i type?
in ur setup hook
so, it's windows CMD or... ?
hey
error:
someone help me
did u do pip install jishaku
yes
can you help me
i have no idea how to help you
same thing:
look at the full error to see if you can help me https://pastebin.com/27VxzE8S
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.
tried upgrading ur pip version?
no
seen
?
try:
code here
except Exception as e:
print(e)
like i said, i have no idea how to help u
.v
list indices must be integers or slices, not str
guess i understood what it meant
guess i need to put .lenght
so it would be interger
to get the variables from the list
So how would you solve this?

what would happens if i use enumerate?
i'm traumatized for life
forbidden means not allowed to send the message idk what its got to do with invite_message
make sure invite_message will always be set to something like you show in the first place
!enumerate
Ever find yourself in need of the current iteration number of your for loop? You should use enumerate! Using enumerate, you can turn code that looks like this:
index = 0
for item in my_list:
print(f"{index}: {item}")
index += 1
into beautiful, pythonic code:
for index, item in enumerate(my_list):
print(f"{index}: {item}")
For more information, check out the official docs, or PEP 279.

also why not just delete_after kwarg instead of calling delete personally
dpy will handle it in backend
and just pass on the forbidden
or even better use interactions and send an ephemeral message that way u wont have to waste an api call on deleting
okay now i received this:
1d6
Roll.sub_roll() takes 1 positional argument but 2 were given
it was just only 1 argument
send code lol
!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'm running into an issue trying to use cogs with discord.Client, does anyone have some time?
u forgot self in seb_roll
self, whatever
does Client support cogs i dont think so but could be wrong i never used client commands.Bot for laif
aliases must go into the command decorator not the function
at this point idek anymore, i've switched from bot to client many times because neither support what I need
I want to use slash commands, but I also want to organize my code
skill issue
sure
which line?
sub_roll function bro
i didn't got you
you could use hybrid commands lmao

i see, but i'm still confuse
i don't know which line. What are the aliases?
oh my god
its ur own code π
how does that work, does it just automatically list as a slash command?
you are passing a default list as a function argument named aliases if you expect that to work for aliases it wont you need to put that into the .command() decorator
it creates both a slash command and a prefix command
line 151
bruh why the fuck did I not learn about this earlier
i've been trying to fix this for hours
all you have to do is
@commands.hybrid_command()
instead of
@commands.command()
skill issue read docs
problem solved
friggin did, on cogs and slash commands π
@commands.command(aliases=[])
@dim cosmos thanks for the tip
glasses 
yw
fixed:
good
good job
okay, line 151... confuse.
put self into the function... uhmm
i need an example
π΅
def something(self):
literally me
you're gonna make us cry holy shit
.
I mean, u can keep it as a static method.

like this?
yes
yay
copilot i am guessing from those comments
^^
wait seriously?
no lol
the function call takes longer
something = [] is over twice as fast
and it's way more readable
thanks
np
!timeit
set()
@shrewd apex :white_check_mark: Your 3.11 timeit job has completed with return code 0.
2000000 loops, best of 5: 104 nsec per loop
!timeit
{*()}
@shrewd apex :white_check_mark: Your 3.11 timeit job has completed with return code 0.
2000000 loops, best of 5: 145 nsec per loop
hmm
!timeit
async with aiohttp.ClientSession() as session:
async with session.get("https://ws.audioscrobbler.com/2.0?method=track.getInfo&username=tbpn&api_key=e739760b740efae08aeef62f0e15d7b7&artist=tyfontaine&track=dummy&format=json&autocorrect=1") as response:
result = await response.json()
result['track']['name]
@dim cosmos :x: Your 3.11 timeit job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<frozen runpy>", line 198, in _run_module_as_main
003 | File "<frozen runpy>", line 88, in _run_code
004 | File "/usr/local/lib/python3.11/timeit.py", line 376, in <module>
005 | sys.exit(main())
006 | ^^^^^^
007 | File "/usr/local/lib/python3.11/timeit.py", line 315, in main
008 | t = Timer(stmt, setup, timer)
009 | ^^^^^^^^^^^^^^^^^^^^^^^^^
010 | File "/usr/local/lib/python3.11/timeit.py", line 123, in __init__
011 | compile(stmtprefix + stmt, dummy_src_name, "exec")
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/tiyimufiho.txt?noredirect
i never knew that split converts numbers into interger when there is no character. Good to know
it doesn't
i got this:
int() argument must be a string, a bytes-like object or a real number, not 'list'
Can you show me an example please?
when entered the sub_roll
read
yeah because str.split doesn't return integers
just a single list of strings
and int(["1", "2", "3"]) doesn't work because that isn't a single cohesive integer
oh gotcha
use a button or hybrid or slash command any interaction component
it seems that i need to turns into INt each
depending on your situation
you could do py string_parts = strings.split() integers = [int(string_part) for string_part in string_parts]
is there a command that converts all stuffs in a list?
map
in python we use list comprehension
i.e. [int(stuffs) for stuffs in a_list]
to convert each stuffs in a list to an integer
guess i'm gonna make a research
guess this works:
for i in range(0, len(test_list)):
test_list[i] = int(test_list[i])
unsupported operand type(s) for +: 'int' and 'list'
if you guys need my code again:
https://paste.pythondiscord.com/olilebojut
why i'm receiving this?
#work command
@nextcord.slash_command(description='Grind for da money')
@cooldowns.cooldown(1, 1800, bucket=cooldowns.SlashBucket.author)
async def work(self, interaction):
chances=random.randint(1,4)
if chances==1:
return await interaction.send('You got nothing. F')
amount=random.randint(1,10)
res=await self.update_wallet(interaction.user,amount)
if res==0:
return await interaction.send('No account has been found, so one has been created for you. Please run the command again after the cooldown!')
await interaction.send(f'You got {amount} coins!')
0|bot | Ignoring exception in command <nextcord.application_command.SlashApplicationCommand object at 0x7fce4350f970>:
0|bot | Traceback (most recent call last):
0|bot | File "/usr/local/lib/python3.8/dist-packages/nextcord/application_command.py", line 906, in invoke_callback_with_hooks
0|bot | await self(interaction, *args, **kwargs)
0|bot | File "/usr/local/lib/python3.8/dist-packages/cooldowns/cooldown.py", line 103, in inner
0|bot | async with _cooldown(*args, **kwargs):
0|bot | File "/usr/local/lib/python3.8/dist-packages/cooldowns/cooldown.py", line 248, in __aenter__
0|bot | async with bucket:
0|bot | File "/usr/local/lib/python3.8/dist-packages/cooldowns/cooldown_times_per.py", line 50, in __aenter__
0|bot | raise CallableOnCooldown(
0|bot | cooldowns.exceptions.CallableOnCooldown: This function is being rate-limited. Please try again in 1794 seconds.
0|bot | The above exception was the direct cause of the following exception:
0|bot | nextcord.errors.ApplicationInvokeError: Command raised an exception: CallableOnCooldown: This function is being rate-limited. Please try again in 1794 seconds.
how can i modify my command to send a message like "You are on cooldown for this command. Please wait x more seconds?"
learn basics of python first smh
make an error handler
try:
#work command
except Exception:
interaction.send(Exception)
i tried this but it didnt work (i get the same error), im not sure what else to do
You need to listen for error event, not sure how it is called in nextcord
It's on_application_command_error
!d nextcord.ext.application_checks.on_application_command_error
nextcord.ext.application_checks.on_application_command_error(interaction, error)```
The event that is fired when an error occurs during application command invocation.
ahhh ok i'll try to put that in my Help cog then
Why the hell is it located in checks
thank you!
hey how would I get this embed to send a link to the channel instead of just the raw text?
if welcome_channel:
embed = discord.Embed(title=f"Welcome {member.name}!",
description=f"Thank you for joining our server! Please take a moment to read the "
f"#{discord.utils.get(member.guild.channels, name='rules')} and introduce yourself in the "
f"#{discord.utils.get(member.guild.channels, name='introductions')} channel.",
color=0x00ff00)
embed.set_thumbnail(url=member.avatar_url)
await welcome_channel.send(embed=embed)
wdym
It comes out like that but I want it to say #introductions and #rules with a "link" to the channel
just the rules link popped up in that message ^
you could just get the channel & mention it
if welcome_channel:
embed = discord.Embed(title=f"Welcome {member.name}!",
description=f"Thank you for joining our server! Please take a moment to read the "
f"{discord.utils.get(member.guild.channels, name='rules').mention} and introduce yourself in the "
f"{discord.utils.get(member.guild.channels, name='introductions').mention} channel.",
color=0x00ff00)
embed.set_thumbnail(url=member.avatar_url)
await welcome_channel.send(embed=embed)β
oooh
discord.utils.get(bla bla).mention
or you could also do guild.get_channel(channel).mention
gotcha thankies :3
π
come on man. I try to access the value of a thing in a list list[0] and it still gives me that error? Why you think it's a error from basics of python?
Is it possible to do a global check for slash commands, if the user id is not in the database, then an error will be displayed?
by user do you mean the author
it's possible yea
how?
which db are u using
postgre
fetch user ids from the table & check if the author id is one of them
if it is do everything normally
if it isn't send an error
I know it. and how to make the most global slash check?
for example
def owner(ctx):
return ctx.author.id == 565627105552105507
in the command you'd just add @commands.check(owner)
okay, i detected that for some reason x is detected as an array, not as a value that should be:
print(x)
if x == "+":
total = total+1
elif x == "-":
total = total-1
else:
total = total+x
print(total)
sub rolling...
1d6
rolling...
[1, '6']
entered while
[2]
[[2]]
[2]
unsupported operand type(s) for +: 'int' and 'list'
Why sometimes python don't detect it as a just value? That's strange
maybe i need to cast?
okay, i discovered the problem, x is being treated as a list not as a value. What is strange
okay i discovered why
when i used append it was creating a list in a list
since the list was already created by my algorith
that's why it wasn't working
i got this error and code is for sending messages to multiple webhooks
import requests
import os.path
import os
import time
def hook():
try:
if os.path.exists('./hooks.txt') == True:
if os.stat("hooks.txt").st_size == 0:
print("\nNo hooks found. Please add Webhook URLs to the hooks.txt file.")
else:
content = input('Enter what the webhook(s) should send: ')
while True:
for line in open('hooks.txt'):
line = line.strip()
req = requests.post(
line,
json = {
"content": content
}
)
statusCode = str(req.status_code) # Thank you Python for not allowing me to use req.status_code directly
if statusCode.startswith('2') == True:
print('[' + str(req.status_code) + ']' + ' Message successfully sent.')
elif statusCode.startswith('4') == True:
if statusCode == '429':
retry = int(req.headers['retry-after']) / int(1000)
print('\nGetting ratelimited. Retrying in ' + str(retry) + ' seconds.\n')
time.sleep(retry)
else:
print('[' + str(req.status_code) + ']' + ' Message not sent.')
elif os.path.exists('./hooks.txt') == False:
print('\nNo hooks.txt file found. Please create a hooks.txt file and add webhook URLs to it.')
except KeyboardInterrupt:
print('\nExiting...')
exit()
hook()
!e
timestamp = datetime.datetime.now() + datetime.timedelta(seconds=60)
fmt_time = discord.utils.format_dt(timestamp, "R")
print(fmt_time)```
@young dagger :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'datetime' is not defined
!e
import datetime
timestamp = datetime.datetime.now() + datetime.timedelta(seconds=60)
fmt_time = discord.utils.format_dt(timestamp, "f")
print(fmt_time)```
@young dagger :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | NameError: name 'discord' is not defined
What? That's how it's supposed to be π«€
Has anyone tried hosting on an old android phone through termux?
so i have a bunch of views and a bunch of cogs
many views are only used by one cog, but some are used by multiple
should i put all the views in a single package views
or only put those used by multiple cogs in views and the rest in their cogs' file
i personally put all my views in their own files
even if they are being used only once
!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.
Code: https://paste.pythondiscord.com/qobotuyehu
Error:
Traceback (most recent call last):
File "C:\Users\root\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\root\Desktop\project\cogs\Utility.py", line 90, in afk
timestamp = int(round(datetime.now().timestamp()))
AttributeError: module 'datetime' has no attribute 'now'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\root\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\root\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\root\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module 'datetime' has no attribute 'now'
anyone?
it's datetime.datetime.now()
ok ty
ok so now it does put it in the database, but when i type a message again it doesn't show me the welcome back message and it doesnt remove it from the db
listener code: https://paste.pythondiscord.com/qobotuyehu
command code: https://paste.pythondiscord.com/egipujuquc
what does that mean
well
why are you connecting to the database multiple times
you're only supposed to connect once
its once in the listener and then one in the afk command itself
what's the point of that
i still need to make it so it connects on when i run the bot lmfao
ok so it does send the message on mention, just when i type it doesnt welcome back and remove it from the db
class CustomBot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.database = None
async def setup_hook(self):
self.database = await aiosqlite.connect("database.db")
async def close(self):
await self.database.commit()
await self.database.close()
await super().close()
use something like this to not connect to it twice
then you can just use bot.database
oooh
i doubt it will fix your issue but at least that way you won't connect to your database every time a message is sent
ok, and that means i can remove the whole aiosqlite.connect(db) on every command/event i use it for?
have you tried seeing if if data runs?
it should, i never touched the code
when i made it, it worked. its ever since the datetime thing error it didnt work
otherwise i never changed the code
i can pull the code out of an older bad bot of mine to double check
so just double checking, this would work, right?
from discord.ext import commands
import os
import aiosqlite
class Bot(commands.Bot):
def __init__(self, *args, prefix=None, **kwargs):
super().__init__(*args, **kwargs)
self.prefix = prefix
self.database = None
async def setup_hook(self):
self.database = await aiosqlite.connect("void.db")
for file in os.listdir("cogs"):
if file.endswith(".py"):
name = file[:-3]
await self.load_extension(f"cogs.{name}")
async def close(self):
await self.database.commit()
await self.database.close()
await super().close()
async def on_message(self, msg):
if (
not self.is_ready()
or msg.author.bot
or msg.guild is None
):
return
await self.process_commands(msg)
nope no intents
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
yeah those are in my main file
ic
asher, u got an idea?
then it should yeah
on that problem^
u have an error handler?
none set up rn
set it up and raise an error
still working on one when i figure that out properly, i had one but idk what happened to it, i lost the code for it lmfao
ok
don't think that prefix = None works there
nvm
prefix=None will do nothing but set bot.prefix=None
try: py -m pip install ...
sometimes windows and installing packages is odd
with the β¦?
it already uses self.prefix though
π
π
what do you think the ... is supposed to be
no, ... is the package
yeah they are, wdym?
yeah i know, but then because i have a db system with prefix, it'll just grab it from there
they already tried that btw
oh then idk
yesterday i think
you didnt' call super().init() inside the init so its' not gonna work you did
what do u mean
yeah they did
oh LMAO
i never read anything if u can help me with my problem LOL
getting ready to go to bed for me
this is the problem
its not sending welcome back message and not removing from the db
so both of us are going to be sleepy i guess
why are you doing data[0][3] too? how do you know there is going to be any data at all?
i told you yesterday im new π
and what if there is no data?
ohk ill try
yeah that's timestamp
the timestamp is in the database tho, thats the weirdest thing
because it send the message if the afk person is mentioned
py -m pip install
and to update it
u need to run that whole line, including C:\
just to be sure
i always do that just to be sure lmfao
the long path is just where it's already executing from
there u go
shrug
and i can run pip install discord.py now?
yeah
alr alr
if that doesnt work, just do py -m pip install discord.py
i thought that didn't work yesterday
yeah
@vital glacier can you use a database browser to see if the user_id as actually added to the database or not?
just use a python debugger or add print statements
what was your create table statement, did you create the user_id field as TEXT/VARCHAR by chance?
genuinely im too stupid to know how to do that properly LOL
i always mess those up, but yet i can figure out how to make a prefix cmd with db etc
10/10 would recommend
what do you mean? just put print everywhere to see how far the code reaches
print(1) print(2) etc
is the cog with that listener loaded? 
i tried using code similar to urs and it works
import sqlite3
import discord
from discord.ext import commands
(connection := sqlite3.connect(":memory:")).execute(
"CREATE TABLE afk (uid INTEGER, reason TEXT) "
)
@(bot := commands.Bot("!", intents=discord.Intents.all())).listen()
async def on_message(msg: discord.Message) -> None:
cur = connection.execute("SELECT * FROM afk WHERE uid = ?", (msg.author.id,))
if cur.fetchall():
await msg.reply("the author was afk")
@bot.command()
async def afk(ctx: commands.Context) -> None:
connection.execute("INSERT INTO afk VALUES (?, ?)", (ctx.author.id, "idk"))
await ctx.reply("afk added")
connection.commit()
bot.run(__import__("os").getenv("DEV_TOKEN"))```
im using the sync driver but that shouldnt matter
Sarth is a real big fan of walrus op
save me a lot of LOC
added a error handler, doesnt throw out anything
i double checked the database code aswell, it should work.
yo sarth, u got any idea? i added an error handler to print out the errors, but it isnt sending anything.
still with the afk problem
is there something wrong with @client.event ?
print, not error handler
no it's because you don't have anything after on_ready
yeah it prints the error
oh okk
how do you know there's an error?
genuinely, idk how it can be anything else
the error handler wont do anything,
you'll have to add manual debug prints for each step
like after getting the data using fetchall() , try printing it
and try printing "SELECT * FROM table" to verify your data
ok so i checked it. it isnt getting past the first time converter
so i assume then that the converters are broken
i think remaking the command and event with humanize is best then?
PS C:\Users.> python3 bot.py
Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.
what do i do to fix this
await interaction.response.defer()
Uninstall all current python versions and install latest stable from official site (https://python.org), make sure to have "add python to PATH" checkmark on
oh ok
so if i do that will i have to reinstall discord.py?
!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...
There is no embed kwarg
If you are new to python, we do not recommend starting learning from a discord bot, as you need this knowledge:
- basics (variables, loops, math, basic types)
- simple data structures (dicts, lists)
- modules and libraries
- functional programming
- object-oriented programming
- async programming principles
Yeah just advising
Cause you are going to lose lots of time if you continue like this
You first defer, then you send
await interaction.response.defer()
...
await interaction.response.send_message(embed=your_embed)```
read the example again
Interaction already responded
response.defer
!d discord.Interaction.followup
Returns the follow up webhook for follow up interactions.
There's also no point in deferring then immediately sending. The thing is you gotta respond to interaction within 3 seconds after you got it, if you are unable to do that, you need to defer first, then respond when needed
I really should do something with dpy or make everyone use disnake
i got the same response with PATH checked
that's not how you fix it..
the issue is that you are using python3 instead of python
python3 will open the microsoft store version
PS C:\Users.> python bot.py
C:\Users.\AppData\Local\Programs\Python\Python311\python.exe: can't open file 'C:\Users\.\bot.py': [Errno 2] No such file or directory
you don't have such file then
hmm
btw i already saw your username yesterday
:((
you forgot to censor it in one of your screen shots
it's not that bad, plus you can always change it
how do i send a modal?
does it have to be intertwined w/ a view?
!d discord.InteractionResponse.send_modal
await send_modal(modal, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a modal.
unnecessary work lol
and no you don't need a view to open it @ionic garden
yeah that's part of an InteractionResponse
you can only open it as part of a response
it can't open by itself
wait does it not work with hybrid commands
hybrid commands use context, not interaction, so no it won't work
that's a big f
sorry for replying so much
was that directed towards me?
yeah
hybrid commands have a lot of limitations, you basically get neither benefits of message commands nor application commands
lmao i don't see what there is to be sorry for
so should i just...switch to app commands at this point
probably lol, or just pick one
well actually, you can still send a modal without a slash command by using a view or some other type of interaction
Anyone know of a way to get all ban entries of a guild before/after a specific date?
!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...
ok, so is there a tutorial on how to make a discord modal?
before and after kwargs
by yours truly
here's an example:
class MyModal(discord.ui.Modal, title = "My Modal"):
name = discord.ui.TextInput(label = "Name")
async def on_submit(self, interaction):
await interaction.response.send_message(f"Your name is {self.name.value}.", ephemeral = True)
docs: https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.ui.Modal
is there a select menu field?
No
Those return all entries before/after a give user though, not a datetime
Oh yeah, lol
even though they could definitely do select menus in modals, and the other way around: text inputs in views
guess i'll have to make do without for now (unless there's something you can do with the audit log) but thanks anyway
i see now why danny ragequit dpy dev
what?? they literally told you how to do it
oh nvm
!d discord.Guild.audit_logs
different conversation.
There's action to sort the bans
Wait, not again
Oooo, they have datetime this time
i really like your bob pfp
!d discord.AuditLogAction.ban

thanks, i'll look into this, my only concern is how well the bot would handle a busy server (for which i also had issues with Guild.bans(...))
thank you he is my favourite AC character
good choice
You can keep the iterator and iterate when you need it instead of converting it to a list instantly
Oh yeah true ty
This method solves all possible issues immediately, I don't wanna sit here and investigate what he has added to path, what is his executable named, what versions he has, whether it was installed from mc store. This method is the easiest, just fixes everything and there are totally no issues with it
Ah yeah this is different error, your original was fixed
.help
a friend told me mysql sucks as a db
is this true
None of dbs suck as long as they meet your needs and are implemented properly
I would say mysql wrapper got weird placeholders and their SQL dialect differs from generic slightly more than others
thats false, but it's a fact that better databases like pgsql exists
Although I only saw it once, so you better see by yourself
anyone that got experience with humanizer?
https://paste.pythondiscord.com/aheroloves
I have this command, I will move the block
with open(output_file, "rb"):
async with ctx.channel.typing():
await ctx.send(file=discord.File(output_file))```
but my question is there a way that I can get the link of the image after sending it (discord link) like this one
`https://media.discordapp.net/attachments/1052225384093061175/1074616755332333598/robin.png?width=434&height=606`
and then I want to save it in the `img_name` variable
I'm trying to use slash commands / hybrid commands for my discord bot.
It seems I can't get it to work with cogs.
Has anyone used hybrid commands before? Could you give me some tips on how to do this properly?
I have
commands.hybrid_command()
if im correct
Keep the message in a var then get it
!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.
!d discord.Attachment.url
The attachment URL. If the message this attachment was attached to is deleted, then this will 404.
thank you very muchhhh
so after sending it right?
ofc this was a stupid question π thank you
embed.set_thumbnail(url=ctx.guild.icon_url)
AttributeError: 'Guild' object has no attribute 'icon_url'```
You can see the available attributes in the docs
!d discord.Guild
class discord.Guild```
Represents a Discord guild.
This is referred to as a βserverβ in the official Discord UI.
x == y Checks if two guilds are equal.
x != y Checks if two guilds are not equal.
hash(x) Returns the guildβs hash.
str(x) Returns the guildβs name.
I guess .icon is what you want
.icon gives you an Asset object. You can get url from that with .url
oh thanks!
A test cog
from discord.ext import commands
from discord.ext.commands import Context
# Here we name the cog and create a new class for the cog.
class Template(commands.Cog, name="template"):
def __init__(self, bot):
self.bot = bot
# Here you can just add your own commands, you'll always need to provide "self" as first parameter.
@commands.hybrid_command(
name="test",
description="This is a testing command that does nothing.",
)
async def test(self, context: Context):
"""
This is a testing command that does nothing.
:param context: The application command context.
"""
await context.send("This works.")
# And then we finally add the cog to the bot so that it can load, unload, reload and use it's content.
async def setup(bot):
await bot.add_cog(Template(bot))
To sync slash commands globally, you need to incorporate this in your bot.py or main.py equivalent:
@bot.event
async def on_ready() -> None:
"""
The code in this event is executed when the bot is ready.
"""
status_task.start()
await bot.tree.sync(guild=discord.Object(id="guild id here"))
This last part ensures that you're loading it forcefully
Don't run tasks and sync in on_ready
Yes, but the commands never shop up in the help menu nor do they get registered by the main file
I will try this
oh? why not and where else would I need to put it
on_ready can be called multiple times, and if that happens, it will try to start the task again and lead to this error
Unless it was cancelled before
!d discord.Client.setup_hook
await setup_hook()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A coroutine to be called to setup the bot, by default this is blank.
To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.
This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") event.
Warning
Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for "discord.Client.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_until_ready "discord.Client.wait_until_ready")...
Override this method instead
#THE COMMAND
@app_commands.checks.has_any_role("Owner","Moderator")
#THE ERROR HANDLER
@test.error
async def on_test_error(interaction: discord.Interaction,error: app_commands.AppCommandError):
if isinstance(error, app_commands.MissingAnyRole):
await interaction.response.send_message("You are not authorized to use this command!")``` The error message is not sent, just "app did not respond"
So, how exactly do I load the cogs now?
Because all this has just made it more, unclear
what does content= do
and why is it a f string
they don't matter, I removed them and nothing changed
It's for the content of the message that's going to be sent
!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.
but you can just leave that out right? I've never had any trouble with just inputting what you want sent
What are you on about
I would just
await send_message("Hello", embed=Embed)```
I'm just saying it's for the content of the message
and it'd always worked
Doesn't matter
It's the same thing
yeah, alright, that's what I was wondering
So why doesn't it send the custom error message?
what's the actual error that gets raised?
add an else clause and raise error there
the actual error is "The app did not respond" and when I added else clause, nothing happened too
no error when you remove the handler too?
nope
then you're probably just not responding to the interaction in time
what's the code for your command?
i'm receiving this error in this part of the code:
print("detected #")
#mark will mark how much occurances it will be for the multi-rollings,
#mark will only store the first value
mark = args_result.split('#')
args_result[0] = mark[1]
mark.pop(1)
for z in range(0, mark):
#here will start the multi-rolling
print("initiating sequence")
resp_sub = f"{z}#"
for x in args_result:
#this is the subroll of keach multiroll from a sequence of rolls
print("initiating rollling")
roll_result = self.sub_roll(x)
print(roll_result)
resp_sub = resp_sub + f"{indice} {args_result[x]} {roll_result}"
store.append(roll_result[1])
resp_sub = + "\n"
else:
#when there aren't a # it will initiate a single roll
resp_sub = ""
for x in args_result:
#this will be a regular roll for each dice in the line, will be stored into store
print("initiating rollling")
roll_result = self.sub_roll(x)
print(roll_result)
if not resp_sub:
resp_sub = f"{indice} {args_result[x]} {roll_result}"
else:
resp_sub = resp_sub + f"{indice} {args_result[x]} {roll_result}"
print(resp_sub)
store.append(roll_result[1])
print(store)```
but even i changing the type to string the error persists
guess it's indice
now i received this:
list index out of range
on console
sucess on habilited
initiating rollling
[[[5], 5]]
1d6 [[[5], 5]]```
await ch.set_permissions(ctx.guild.default_role,view_channel=True,send_messages=False)
view channel perm is edited btw why not send messages
What
the send messages permisison is not denied
Is not what
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.
list index out of range
https://paste.pythondiscord.com/lawoquyeso
Sucess: Bot is connected to discord!
Ping.py is ready
Roll.py is ready
started rolling...
indz: 1
indz: d
indz: 6
['1d6']
testing # occurence
sucess on habilited
initiating rollling
[[[3], 3]]```
console
it basically stops at line 91
better, at line 80
no, i am interacting in time
hello, I have once again returned
for f in path.glob("[!_]*.py"):
print("Extension(s) loading...")
await self.load_extension(f"cogs.{f.stem}")```
I have a file that ends with .py and does not begin with _
Why does it not run properly?
not even the printing happens, so that indicates that it doesn't see the file in the folder i specified
how do i test a thing if it can be true or not?
or better
how to check if the array have array inside the array?
Roll.py is ready
[[0, 1], '+']
calculating rest
calculating rest
[[[0, 1], '+'], [[1, 2], '-']]
calculating rest
calculating rest```
the first one just had one array
and gave me this error:
string index out of range
okay nevermind
i found what was happening
How to send a specified post forum using webhook? Can help~?
okay, why this don't work?
indice = [[[0,1], '+']]
print(indice[indx][1])
is there a test command?
Why "{indice[indx][1]} {x}" is not working?
#this will be a regular roll for each dice in the line, will be stored into store
print(x, indx)
roll_result = self.sub_roll(x)
if not resp_sub:
resp_sub = f"{x}"
for roll_index in roll_result[0]:
resp_sub = resp_sub + f"({roll_index})"
resp_sub = resp_sub + f"[{roll_result[1]}]"
else:
resp_sub = resp_sub + f"{indice[indx][1]} {x}"
for roll_index in roll_result[0]:
resp_sub = resp_sub + f"({roll_index})"
resp_sub = resp_sub + f"[{roll_result[1]}]"
store.append(roll_result[1])
print(resp_sub)```
guess now i know what hhappened
indz is being the next instead of previous
it should be indz-1
@slate swan what kind of algorithm are you trying to implement
I've seen you struggling with it for like 4 days so far
And I suspect it might be xy problem
!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'm struggling with this algorithm:
https://paste.pythondiscord.com/lilesavize
the algorythm to make operations
I mean what is it supposed to do
first it's suppose to calculate the division, then multiplication then sum and subtraction
using the indice as a reference to number position and which operand itwas using
it's suppose to roll dices, show their result, calculate the subtotal then total and then output it
it's a dice roll algorythm
like roll 1d6
or 1d20
as you can see it's rolling dices:
the result show 3
at the final
did you got me?
What bothers you to use randint then
well, because it's a function to roll the dice, to make a roll it's basically using randint
alll dices show interger outcomes
and it's also suppose to get all dices and calculation resulst and show it at final
There can be unlimited amount of dices?
yes
for example i roll 1d6+1d6, and it brings 4 and 5, so it's suppose to the final result being 9
I will be afk for now, i'm going to GYM, when i'm back i will see the message
please ping during reply
so i won't be lost with others
Either I don't get something or you overcomplicated it
Lemme try and write a function for that
what do u wanna achieve?
