#discord-bots
1 messages Β· Page 1045 of 1
yeah, I learned most things I know about python thanks to discord bots
it's easier to learn if you have a project
I'm working to create a welcome bot for when new people join a server. I'm making it for a couple friends (each has their own discord server). On my test server it's easy enough to hard code the general channel's ID, but if the bot is being used on multiple servers/guilds, how do I send the welcome message to the general channel of JUST the server that has that new member?
I'd say the hardest part is actually figuring out which channel to send that to
Are we assuming that in each server, the general channel is called "#general"?
you could make it so people can set the welcome channel
That requires a bit more setup (a database)
yeah
If you're willing to put that effort in, I can walk you through that as well
But you did say you were new, so it's probably best to get your feet wet first before doing anything crazy
yep! I've basic loop that works for finding my general channel
for guild in bot.guilds:
for channel in guild.channels:
if channel.name == 'general':
general_channel = channel.id
print(f'General Channel ID: {general_channel}')
but right now, this only works because it's only one guild π
Instead of iterating the guilds, you should be doing Member.guild in your on_member_join
Then just look for the general channel in Member.guild.text_channels
You're on the right track, but fyi discord.py has a discord.utils.get() method that does this same thing but in a much easier fashion:
import discord
channel = discord.utils.get(guild.channels, name='general')
oh nice! yeah, that's much better. That's also good to know @pliant gulch I can play around with both of those and see how each works
Yea, just combine what me and robin said
Then it'll only send in the guild which just had a member join
π Much appreciated to ya both!
can i start Cog task elsewhere than in __init__() for example in on_ready() ?
Why would you need it there? I dont really recommend running it there.
because the task checks for new comic strip and posts it to certain guild channel if there's new one
!d discord.ext.commands.Bot.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...
I recommend using this
!d discord.ext.commands.Cog.cog_load
await cog_load()```
This function *could be a* [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A special method that is called when the cog gets loaded.
Subclasses must replace this if they want special asynchronous loading behaviour.
Note that the `__init__` special method does not allow asynchronous code to run
inside it, thus this is helpful for setting up code that needs to be asynchronous...
Because the API returned -1: https://gdbrowser.com/api/profile/
Try printing response.json()
yea but the command i use makes it so {username} is a player in the api
if it type https://gdbrowser.com/api/profile/robtop
That's what you want it to do, but because you never change username it is always an empty string and becomes https://gdbrowser.com/api/profile/ π
how do i make this into a str variable then?
Add an argument to your view, called username and set self.username = username
This is a parameter, which is different in scope. You can have a variable inside of a function, and globally, at the same time without them affecting each other
This is what is happening here
After doing this, change {username} to {self.username} and it should work as expected! I recommend removing username = "" afterwards so that it isn't confusing anyone
inside of the view=Button()?
Instead of having a global variable shared by all people who use your bot at the same time, you now have a username for each person that used your command . Before people couldn't use your command at the same time
Inside of def __init__(self, HERE):
For you, this would be def __init__(self, username):
Not exactly, you want to put self.username = username inside of the actual body. Have you worked with attributes before?
Right, but, I don't think this solves the problem I'm having. Also, if I were to do this how am I supposed to get the specific guild? It's being ran in a loop so it doesnt have like a context from a command
Did you see what's wrong?
def __init__(self, username):
super().__init__(timeout=None)
self.username = username```
this is right?
Yes that's great!
response = requests.get(f"https://gdbrowser.com/api/profile/{self.username}")```
Yup 
ok
Traceback (most recent call last):
File "C:\Users\a\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\interaction_bot_base.py", line 1264, in process_application_commands
await app_command.invoke(interaction)
File "C:\Users\a\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\slash_core.py", line 689, in invoke
raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Button.__init__() missing 1 required positional argument: 'username'
hm
You are looking at the second traceback, can you copy the one above?
Do you see where you need to change? There is a line inside of the command you have forgotten to change
hm
if i get an error is there a way to handle it while not being command specific
like respond
i think i found it? i've added view=Button(username)
You can use the <code>on_command_error</code> event to handle errors that occur when a command is executed. You can also use the <code>@bot.command(error=...)</code> decorator to handle errors that occur when a command is executed. The decorator takes a callback that will be called with the context and the error. The event takes a callback that will be called with the context, the error, and the original command (if any). If you want to handle all errors, you can use <code>@bot.event</code> instead of <code>@bot.command</code>.
Yes that is it, because without adding username there you are only passing self to __init__.py
You can setup an error handler which is a type of event. Which library are you using?
just discord.py
im a little confused by this
@work.error
async def work_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
em = discord.Embed(title=f"**Wait a little bit lmao**",description=f"Try again in `{int(error.retry_after/60)}` minutes.", color=discord.Colour.red())
await ctx.send(embed=em)
heres an example of an error handler i have now
You can override this or just add the decorator to add the listener https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.on_command_error
Yes, this is command-specific
theres an event for it
@bot.event
async def on_command_error(ctx, error):
...
ah ok
!d discord.ext.commands.on_message_delete
No documentation found for the requested symbol.
@client.command()
async def item(ctx, item=None):
if item==None:
await ctx.reply("You must specify an item")
con = sqlite3.connect("TEST.db")
con.row_factory = sqlite3.Row # Turns the result rows into dictionary objects
cur = con.cursor()
sql_params1 = {
'userid': ctx.author.id
}
result = cur.fetchone()
if item in ('daily', 'dailybox'):
cur.execute("SELECT DailyBox FROM Database WHERE User_Id = :userid", sql_params1)
dailybox = result['DailyBox']
await ctx.reply(f"Number: {dailybox}")
em=discord.Embed(title=f"Daily Box", description=f"> `{dailybox}` dailyboxes owned\n> A loot box you get from the daily command, you can't get anything good from this, right?/n/n")
await ctx.reply(embed=em)```
This works until the `if item in ('daily', 'dailybox'):` part
can anyone help?
for example the command would be
,item dailybox
no response no error msg
so what doesnt work
the if item part
doesn't py have a None and Null?
they are the same thing
somehow I thought they were different
doesnt change anything (i tried both ways)
u are trying to do with argument or command
couldn't you just set the default value to something instead of null and then throw an error or stop the code if it's null
@keen mural
its None
what
you literally said they're the same π
what are u trying to do in that command
for example the command would be
,item dailybox
but we dont use null anymore ig
alr
so dailybox is argument and item is command?
async def item(ctx, *, item=None):
u need a star there
ok
@loud junco
can anyone help
hmm
maybe set item: string @keen mural
and make an error handler for missing argument
name string is not defined
doesnt work
item: str
ppft
if arg in ['daily', 'dailybox']:
i have that
also isn't that supposed to set its default value instead of rule
just make it arg
dont mess up ur life
type* not rule
can la
its still working right?
async def item(ctx, *, arg: str):
that just makes nothing work again
@client.command()
async def item(ctx, itemname=None):
if itemname==None:
await ctx.reply("You must specify an item")
return
con = sqlite3.connect("TEST.db")
con.row_factory = sqlite3.Row # Turns the result rows into dictionary objects
cur = con.cursor()
sql_params1 = {
'userid': ctx.author.id
}
result = cur.fetchone()
if itemname in ['daily' or 'dailybox']:
cur.execute("SELECT DailyBox FROM Database WHERE User_Id = :userid", sql_params1)
dailybox = result['DailyBox']
em=discord.Embed(title=f"Daily Box", description=f"> `{dailybox}` dailyboxes owned\n> A loot box you get from the daily command, you can't get anything good from this, right?/n/n")
await ctx.reply(embed=em)```
just make it arg π
why
when all lowercase argument
what u send doesnt work
?\
ur using error handler?
disable it for awhile and try
@client.command()
async def item(ctx, *, arg: str):
if arg == None: #this wont work make a error handler for this
await ctx.reply("You must specify an item")
return
con = sqlite3.connect("TEST.db")
con.row_factory = sqlite3.Row # Turns the result rows into dictionary objects
cur = con.cursor()
sql_params1 = {
'userid': ctx.author.id
}
result = cur.fetchone()
if arg in ['daily' or 'dailybox']:
cur.execute("SELECT DailyBox FROM Database WHERE User_Id = :userid", sql_params1)
dailybox = result['DailyBox']
em=discord.Embed(title=f"Daily Box", description=f"> `{dailybox}` dailyboxes owned\n> A loot box you get from the daily command, you can't get anything good from this, right?/n/n")
await ctx.reply(embed=em)
@keen mural
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'NoneType' object is not subscriptable
try this @keen mural
then its this problem
cur.execute("SELECT DailyBox FROM Database WHERE User_Id = :userid", sql_params1)
dailybox = result['DailyBox']
em=discord.Embed(title=f"Daily Box", description=f"> `{dailybox}` dailyboxes owned\n> A loot box you get from the daily command, you can't get anything good from this, right?/n/n")
await ctx.reply(embed=em)
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'NoneType' object is not subscriptable
what do u input
,item daily gives that error
what is NoneType
idk
no idea
whats wrong with this
When using slash commands with auto sync true, when I run my application, it shows warning for the guilds in which it does not have perms to create slash commands. Is there a way to not to raise that warning but get the list of guilds where it does not have perms?
bro what
wtf
LMFAOOO
!ban 833379032728600586 Not acceptable conduct here.
:incoming_envelope: :ok_hand: applied ban to @thorn surge permanently.
no indentation + he informed mods for slangs
Wtf
ngl that was funny
can anyone help??
I think you just have to try except
Try except where?
Oh if ur auto syncing then Iβm not sure
Iβm not sure how ur library sync but you can just catch discord.Forbidden
hmm
hey, an error gets raised when i run my bot that says Package operation failed.
anyone know how to fix this?
which package failed?
and discord (1.7.3) depends on discord.py (>=1.7.3), discord (>=1.7.3,<2.0.0) requires discord.py (>=1.7.3).
Because discord.py (1.7.3) depends on aiohttp (>=3.6.0,<3.8.0)
and no versions of discord.py match >1.7.3, discord.py (>=1.7.3) requires aiohttp (>=3.6.0,<3.8.0).
Thus, discord (>=1.7.3,<2.0.0) requires aiohttp (>=3.6.0,<3.8.0).
So, because python-template depends on both discord (^1.7.3) and aiohttp (^3.8.1), version solving failed.
at venv/lib/python3.8/site-packages/poetry/puzzle/solver.py:241 in _solve
237β packages = result.packages
238β except OverrideNeeded as e:
239β return self.solve_in_compatibility_mode(e.overrides, use_latest=use_latest)
240β except SolveFailure as e:
β 241β raise SolverProblemError(e)
242β
243β results = dict(
244β depth_first_search(
245β PackageNode(self._package, packages), aggregate_package_nodes
/home/runner/valorant-help-bot/venv/lib/python3.8/site-packages/setuptools/command/install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
warnings.warn(
exit status 1```
i think the discord one π
Do you have an external requirements. txt?
yeah
check your .toml and .lock file and check if discord's version is set to 1.7.3
You are using correct headers?
headers must include token
do i set both of them to 1.7.3?
alr
Wait other token work?
its installed, try it
IDK probably you cannot use this method or you need some different headers
try to kill your repo by typing kill 1 in shell and restart it
idk check if your token is correct. I never used it srry
it should work tho
well, some more things in the discord documentation doesn't work so probably this is the same case
previously it added the libs up until flask but now its stuck on opencv-python
it takes some time
oh and it failed
Because no versions of discord match >1.7.3,<2.0.0
and discord (1.7.3) depends on discord.py (>=1.7.3), discord (>=1.7.3,<2.0.0) requires discord.py (>=1.7.3).
Because discord.py (1.7.3) depends on aiohttp (>=3.6.0,<3.8.0)
and no versions of discord.py match >1.7.3, discord.py (>=1.7.3) requires aiohttp (>=3.6.0,<3.8.0).
Thus, discord (>=1.7.3,<2.0.0) requires aiohttp (>=3.6.0,<3.8.0).
So, because python-template depends on both aiohttp (^3.8.1) and discord (^1.7.3), version solving failed.
at venv/lib/python3.8/site-packages/poetry/puzzle/solver.py:241 in _solve
237β packages = result.packages
238β except OverrideNeeded as e:
239β return self.solve_in_compatibility_mode(e.overrides, use_latest=use_latest)
240β except SolveFailure as e:
β 241β raise SolverProblemError(e)
242β
243β results = dict(
244β depth_first_search(
245β PackageNode(self._package, packages), aggregate_package_nodes
/home/runner/valorant-help-bot/venv/lib/python3.8/site-packages/setuptools/command/install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
warnings.warn(
/home/runner/valorant-help-bot/venv/lib/python3.8/site-packages/setuptools/command/install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
warnings.warn(
exit status 1```
so instead of import discord i js do import disnake
to implement it in your application, replacepy import discordwithpy import disnake as discord
ye replace every discord from import to disnake
then use packager in replit to install disnake
i just made it from disnake.ext.commands import ____
ye
pip install disnake right
how do i do that ?
go to packager under commands
disnake 2.5.1 right
idk the version but just add it
alr
at least problem solved
my friends server got nuked but my bot is in there and have admin any command i can use to give me admin or creat a channel?
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
ye you can
if you need admin, then create a role with admin perms and add it to yourself
could you help me i tried a mute command that gives me perms but it didnt work lol
you got code for that
im trying to save his server before all his members leave
role= await ctx.guild.create_role(name= "admin", perms= disnake.Permissions(administrator= True))
await ctx.author.add_roles(role)```
implement it in your program
in a command
Why don't you just ask him to give you the permissions himself
idk it can be used for mal purpose also
cuz hes offline and his server got nuked
try to make a new repl
alright, ill try that thank u for all the help btw i appreciate it
\π
Hey @robust fulcrum!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
disnake undified
i gotta download package md
import os
import discord
from dotenv import load_dotenv
from discord.ext import commands, tasks
from discord.ui import Button
intents = discord.Intents.default()
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
bot = commands.Bot(command_prefix='%', intents=intents)
@bot.event
async def on_ready():
print("bot is resdy")
@bot.command(name="invite")
async def embed(ctx):
embed = discord.Embed(
title="Bot Invite Link",
description="Click on the button below to invite the bot :)",
color=discord.Color.green())
button = Button(
label="invite",
style=discord.ButtonStyle.link,
url=
"https://www.google.com/search?q=discord.py+buttons&oq=&aqs=chrome.1.69i176j35i39i362.-1j1j7&client=ms-android-oppo&sourceid=chrome-mobile&ie=UTF-8"
)
view = View()
view.add_item(button)
await ctx.send(embed=embed, view=view)
bot.run(TOKEN)
I made this command but when i run there's no error but comamnd not working
Pls anyone help me with this
hey so, im not sure if you gotta be rlly expieranced to ask shit so uh yeah. not the best at discord.py but still gonna ask
im making a gate keeper system, and when a person submits a application there answers gets saved to a db (plus the vars of the forum ofc, using forums ui feature)
i need a way to get the id of the user (mongo document id) from later up above in the code where i am making a menu to approve/deny the user from a message it sends. not sure if im just being dumb but i cant think of any way to get the id of the user who created the application as interaction.user just will give me the person who is clicking the menu ofc
again not the most expieranced at discord.py as ive only started a few weeks ago and just started messing around with dropdowns today. so im not sure if im just missing a easy way to do this lol
you don't appear to have message content intents enabled
if you're subclassing the forms class, you can pass in any number of parameters to your __init__ function. Simply pass in ctx/interaction (depending what type of command you're using) to your subclass and add it as a parameter
Still not working
does your bot application have them enabled?
im sorry im very lost lmaoo. mind if i dm u a paste url of my code?(paste.pythondiscord.com)
its not much just rather not send it here and it will help explaining what i mean as i explained that wrong i think
you can just send it here :p
how can i listen in a cog for the bot to be ready?
this is what i have currently
import disnake
from disnake.ext import commands
from colorama import Fore, Back, Style
def setup(bot):
bot.add_cog(events(bot))
class events(commands.Cog):
"""Useful Features for Bot Development."""
def __init__(self, bot: commands.Bot):
self.bot = bot
print('Loading Events cog')
@commands.Cog.listener()
async def on_ready(self):
you've got your indents messed up
and your setup function should go after you define your class
Ye
so like
import disnake
from disnake.ext import commands
from colorama import Fore, Back, Style
class events(commands.Cog):
"""Useful Features for Bot Development."""
def setup(bot):
bot.add_cog(events(bot))
def __init__(self, bot: commands.Bot):
self.bot = bot
print('Loading Events cog')
@commands.Cog.listener()
async def on_ready(self):
toggle it off, wait a bit, and toggle it back on, see if that fixes your issue
so sorry that my code is a mess π
no, you've got your listener outdented, and your setup function should go outside the class
you want the users id?
Still not working
no
lmao please put the setup function in the right spot for me or give an example so i can understand.
k
forum
my braincells are acting like the dvd logo rn
this chat is just all over the place lmao, wish there was threads or something in here auto created
import disnake
from disnake.ext import commands
from colorama import Fore, Back, Style
class events(commands.Cog):
"""Useful Features for Bot Development."""
def setup(bot):
bot.add_cog(events(bot))
def __init__(self, bot: commands.Bot):
self.bot = bot
print('Loading Events cog')
@commands.Cog.listener()
async def on_ready(self):
pass
def setup():
bot.add_cog(events)
or something im on mobile
whats the pass for?
7.4. The pass statement
pass_stmt ::= "pass"
``` [`pass`](https://docs.python.org/3/reference/simple_stmts.html#pass) is a null operation β when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed, for example:
```py
def f(arg): pass # a function that does nothing (yet)
class C: pass # a class with no methods (yet)
wym? takes the answers from discord.py ui forum -> puts it in the db
I need ot get the user id so i can access the db tho
the submitter..
ill need to know how youβre accessing data from the forum
is this laid out wrong?
import disnake
from disnake.ext import commands
from colorama import Fore, Back, Style
class events(commands.Cog):
"""Useful Features for Bot Development."""
def setup(bot):
bot.add_cog(events(bot))
def __init__(self, bot: commands.Bot):
self.bot = bot
print('Loading Events cog')
@commands.Cog.listener()
async def on_ready(self):
print(Fore.GREEN + 'Connected!' + Fore.WHITE)
print(Fore.GREEN + 'Bot is ready!' + Fore.WHITE)
print(Fore.CYAN + 'Waiting For Commands' + Fore.WHITE)
bot.get_guild(798726719573065749)
channel = bot.get_channel(798726720181633047)
await channel.send('Bot Online!')
embed = disnake.Embed()
embed.title = f"**Online**"
embed.description = f"[`{datetime.datetime.now().strftime('%b-%d-%Y`] @ [`%I:%M:%S')}`]\n\n" \
f"- Bot account: `{bot.user.name}`\n" \
f"- Bot ID: `{bot.user.id}`\n" \
f"- Guilds: `{len(bot.guilds):,}`\n" \
f"- Users: `{len(list(bot.get_all_members()))}`\n" \
f"- Disnake Version: `{disnake.__version__}`\n" \
f"- Developer: `whiskeythefox$7339`\n" \
embed.set_footer(text="Logging System")
GUILD_ID = 798726719573065749
CHANNEL_ID = 798726720181633047
location = bot.get_guild(GUILD_ID).get_channel(CHANNEL_ID)
await location.send(embed=embed)
pass
def setup():
bot.add_cog(events)

no its fine
bro from discord lmao
itsa built in feature
no it's alr, thought you don't need the setup() inside your class
oh
never used it
ill have to check
where and how are you creating the forum?
*forum
e
E
the def setup(bot):
?
!d discord.ui.Modal
class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.
This object must be inherited to create a modal popup window within discord.
New in version 2.0.
Examples...
the one that's inside your class, yes, that one isn't necessary
@indigo pilot this?
Bro use fields
doc for it please?
!discord.Embed.add_field
!d discord.Embed.add_field
add_field(*, name, value, inline=True)```
Adds a field to the embed object.
This function returns the class instance to allow for fluent-style
chaining. Can only be up to 25 fields.
Damn
discord ui
is it a modal
yeah
someone send a screenshot of what a modal looks like
class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.
This object must be inherited to create a modal popup window within discord.
New in version 2.0.
Examples...
Rehold can u send code
even or that dosnt really matter lol..
- just look at the code i sent
- the user id is a user id, still there in the code
i did?? π§
I made a modal example for discord.py, maybe it's helpful? https://github.com/Rapptz/discord.py/blob/master/examples/modal.py
Again
hmm what about a without inheriting from ui.Modal
just instantating
import discord
from discord.ext import commands
from discord.ui import Modal, TextInput
@bot.command()
async def test(ctx: commands.Context):
modal = Modal(name = βTestβ)
actually idk
never used modals or buttons
just select menus
What's the issue
tbf, what they're asking for is kinda basic python subclassing stuff
class A:
def __init__(self, arg1, arg2, ...): # you can add as many params as you'd like
self.arg1 = arg1
self.arg2 = arg2
...
a = A("a", "b", ...)
im using disnake not discord.py
it's basically the same thing iirc
What's the issue
for the 3rd time, ^
!d disnake.Embed.add_field
add_field(name, value, *, inline=True)```
Adds a field to the embed object.
This function returns the class instance to allow for fluent-style chaining.
Same
thx
How did u send the modal can u show
the forum? via button
view=Start()
https://Rehold.is-gay.eu/fAu9JXm6
https://Rehold.is-watching-you.xyz/6zCTlJh1
(pls dont be flagged istg)
yeah, so, @indigo pilot, I believe this is what you're looking for
yeah but like where would i even use this at? i know bout this but not where to use it lol
just pass in interaction.user.id to Start() and add it as a param in your __init__
lol
how do i make my bot reply to a specific message ? (command in a cog)
do you got the id of this specific message
do you have the message's ID and the channel's ID?
no i mean if i send hello it shud reply with a message
idk how to make this cmnd in a cog
oh, are you using slash or prefix commands?
prefix
await reply(content=None, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shortcut method to [`send()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context.send "discord.ext.commands.Context.send") to reply to the
[`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") referenced by this context.
For interaction based contexts, this is the same as [`send()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context.send "discord.ext.commands.Context.send")...
no not tht
are we allowed talking about discord.py here too
Or just questions
wdym?
just like, gen chatting lol
stuff that aint questions but still related to discord.py
@bot.listen()
async def on_message(message):
if message.content == "purple":
msg = 'purple'.format(message)
await message.add_reaction(':purple_square:')
how to make this in a cog
class discord.ext.commands.Command(*args, **kwargs)```
A class that implements the protocol for a bot text command.
These are not created manually, instead they are created via the
decorator or functional interface.
not really sure π€·
how can i do that? can i like add interaction to def init(self): or what :p
as well currently i just got self. only got interaction in the button ui
sure
ah well then, rate this amazing command layout
https://Rehold.is-watching-you.xyz/AIqxrAww
some people hate it as cogs are supposed to be grou;s. and some love it LMFAO
just so used to js 
tyty
guildMember(...).py & manage(...).py π
How to fix this i am using get_prefix Function
LOL
you're probably not calling the function
?
you dont call it
oh
What i am supposed to do there?
use bot.command_prefix or ctx.prefix instead ig
code?
that doesnt make sense one bit
whats the point of not defining it in the constructor
they're trying to get the bot's prefix...?
nvm I took it the wrong way, my bad
async def get_prefix(bot: commands.Bot, message: discord.Message):
db = sqlite3.connect('prefix.db')
cursor = db.cursor()
cursor.execute(f"SELECT prefix FROM prefix WHERE guild_id = {message.guild.id}")
result = cursor.fetchone()
if result is not None:
return f"{result[0]}"
else:
return "-"```
How do I not raise an error and check that I don't have slash commands permissions in a server?
@slate swan is it wrong?
hm, isnt it a synchronized function?
No, can be anything
Means?
are you calling it by using await?
and iirc, you got to do something like
return (result)(bot, message)
or am i done for
No
Result is a tuple...
can you help me create a simple example of an embed through disnake. im having issues trying to figure it out
nothing, ill just be off, i need sleep
Fetchone()*
no......
try to call it using await
yes
It isn't? Hmm okay, never used sqlite so I don't remember the return value
its a tuple, its literally 4 am π i need sleep
Can anyone help me too?
I want it shows the prefix not returning the prefix that is found though using the commands work fine with it*
just use bot.command_prefix then, as suggested earlier
What module
It gives the same thing
This one
eh?
!d discord.ext.commands.Context.invoked_with is also there
Wait wrong one
!d discord.ext.commands.Context.prefix
The prefix that was used to invoke the command. For interaction based contexts,
this is / for slash commands and u200b for context menu commands.
This one ^^^
Where i define this?
how can i get my bots pfp
!d discord.ClientUser.avatar
property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/master/api.html#discord.Asset "discord.Asset") for the avatar the user has.
If the user does not have a traditional avatar, `None` is returned.
If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.ClientUser.display_avatar "discord.ClientUser.display_avatar").
umm how do i refrence that in my code
bot_instance.user.avatar
Ok
isnt there also
await bot.get_prefix(message)
!d discord.ext.commands.Bot.get_prefix
await get_prefix(message, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves the prefix the bot is listening to
with the message as a context.
Changed in version 2.0: `message` parameter is now positional-only.
How do i fix it
Put an arguement * in front of the arguement for the new prefix in the function
When used It is giving prefix ('-'),
@commands.Cog.listener()
async def on_message(self,message):
if message.content == "purple":
message = 'purple'.format(message)
await self.message.add_reaction('πͺ')
line 22, in on_message
await self.message.add_reaction('πͺ')
AttributeError: 'replys' object has no attribute 'message'
reply
?
no need for self lol
hunter go to sleep you dont know what youre talking about
just await message. ?
disnake
line 375, in _run_event
await coro(*args, **kwargs)
TypeError: on_message() takes 1 positional argument but 2 were given
its not in a class
class replys(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_message(message):
if message.content == "purple":
message = 'purple'.format(message)
await message.add_reaction('πͺ')
it needs a self parameter, no?
class replys(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_message(self, message):
if message.content == "purple":
await message.add_reaction('πͺ')```
i wonder why he's using format
it probably wasnt in the same line lmao
Β―_(γ)_/Β―
No need for process commands here
idk , it looked like it wouldn't work
Yeah
Looks weird i doubt that will work
then overwriting message with a str
i guess this is in a file called replys.py
if they want to change message they need to use message.edit probably
i wish these would be part of the api somewhere
yeah.
that's in the doc only, as far as I can see ?
If I'm trying to create script that would run on a specific day at a specific time, what would be the best way going about that?
I intend to use the Discord API because my script includes using user IDs, running them through the Discord API to create them as discord objects, and delete them through a criteria.
but yes thats better than nothing @pliant gulch
^ see here
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
For example, on June 1, 2022 at 1 PM, I want x to happen using the Discord API, and then at the same time on July 1, 2022, August 1, 2022 ... forever
Not quite sure I understood what that meant
But the event does exist, not just in the documentation but in the API as well
^^^^
just curious for hyperlinks, what's the actual way to bold text
[**text**](url)**[text](url)**
im sure the first one works, dk about 2nd
id prefer a task.loop , and checking datetimes
what i was envisioning was something more like ABC I guess
something that is part of the runtime contract (maybe on GroupMixin for example)
If I understood you correctly, you can just subclass the client and override _get_state with a custom state class with a new parse_message_delete
class CustomState(ConnectionState):
def __init__(self, **kwargs: typing.Any):
super().__init__(**kwargs)
def parse_message_delete(self, data: dict[str, typing.Any]) -> None:
self.dispatch("message_delete", data) # add your changes
class Client(Client):
def __init__(self, token: str) -> None:
super().__init__(token)
def _get_state(self, **kwargs: typing.Any) -> CustomState:
return CustomState(dispatch=self.dispatch, handlers=self._handlers, hooks=self._hooks, http=self.http, **kwargs)
@livid hinge 
You could use celery for that, but for tasks that run more often i'd recommend using built-in task decorator
Huiiiii
this commnd dosent work now and dosent show any error
Im pretty new to coding bots, does anyone know a vid that can show me how to make a bot add a role to a member after they type something
you can use an on_message event and check if they typed what you wanted
then use message.author.add_roles to add role
k thx
Nvm my bad I thought he wrote message.reply sorry
why doesnt this work?
@bot.event
async def on_message(message):
if message.content == 'he':
await message.reply("react with checkmark")
async def on_raw_reaction_add(reaction, user):
if reaction.emoji == ":white_check_mark:":
Role = discord.utils.get(user.server.roles, name="Dallas Cowboys")
await user.add_roles(Role)
do u mean a command or just that
this is actually close to what I was looking for, thanks
Anyone know how I can timeout someone using a bot
!d discord.Member.edit has a kwarg for the same
await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timed_out_until=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the memberβs data.
Depending on the parameter passed, this requires different permissions listed below...
it's message.guild.roles
Not user.server.roles
im dumb
Server is called guild
@feral lichen i just now realized what you want
yes
I changed it
to
looks to me like you need
@bot.eventdeco on theon_raw_reaction_addawait bot.process_commands(message)in youron_message
What does time_out_until is?
can we have custom emoji in drop down menu?
Check the original message
deco?
decorator
that wouldnt work still
@supple thorntell me
theres a Member method for that
Did you put the decorator like blue asked you to
What
.
yes still lmao
!d discord.on_raw_reaction_add
discord.on_raw_reaction_add(payload)```
Called when a message has a reaction added. Unlike [`on_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_reaction_add "discord.on_reaction_add"), this is
called regardless of the state of the internal message cache.
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
yea like a doc is gonna help that i already looked at
@feral lichen there is no user
i see
It's only payload
It just did help you
do you need to use emoji.name ?
That's why i was confused
@supple thorncan we have custom emoji in drop down menu?
I thought the on_raw_reaction_add was in the message event
Since there was no decorator
is there any possible way you could write this? seems like a puzzle :/
payload.emoji is a PartialEmoji object tho isnt it
We don't spoonfeed you
i know
what is the code you have now
i was typing i dont want spoonfeeds just asking lol
Yeah show the updated code
so im making a joke command
def get_joke(Theme):
api = "https://v2.jokeapi.dev/joke/",Theme,"?blacklistFlags=racist"
r = requests.get(api)
json_data = r.json()
if json_data["type"] == "twopart":
return "\n".join([json_data[x] for x in ["setup","delivery"]])
elif json["type"] == "single":
return json_data["joke"]
client.command()
async def joke(ctx, theme):
joke = get_joke(Theme=theme)
mbed = discord.Embed(
title=f"Joke of theme: {theme}",
description=joke
)
await ctx.channel.send(embed=mbed)
but i get:
No connection adapters were found for "('https://v2.jokeapi.dev/joke/', 'Dark', '?blacklistFlags=racist&type=twopart')"
@bot.event
async def on_raw_reaction_add(payload):
if payload.emoji == ":white_check_mark:":
Role = discord.utils.get(payload.member.guild.roles, name="Dallas Cowboys")
await payload.add_roles(Role)
ight
i think they actually might want name if its a standard emoji
i tried already
Unicode too
it doesnt make a difference
\β
there is no way in hell payload.emoji is ever gonna be equal to a string π€£
Try this
i dd
Replace your string with the unicide version of the emoji
did* doesnt do anything
h e l p
because you didnt concat
the url .. it did a tuple of the url parts instead
You facepalm at us when you're asking us for help
no im face palming because im confused and my brain hurts
@feral lichen are you sure the event is triggering?
so how do i concat without making it a tuple
i did
@feral lichen also do you have intents?
So it prints something?
indeed
problem is here
api = "https://v2.jokeapi.dev/joke/",Theme,"?blacklistFlags=racist"```
Can the bot see the message that you're reacting to?
@feral lichen use str(payload.emoji)
how may i create an invite to the overall server? (not pointed to a specific channel)
you can eithee do an f-string , or do "".join(("http...", Theme, "sfjlffv"))
(or use + instead of ,)
i iwll use +
invites are always binded to channels , not a sever
ah really
is that sm new
interesting. Without any specific emoji an error occurs saying AttributeError: 'RawReactionActionEvent' object has no attribute 'guild'
do they actually take you directly to the specific channel they were created for?
!d discord.RawReactionActionEvent.guild_id
The guild ID where the reaction got added or removed, if applicable.
in that case, id like my bot to create an invite when it joins a server, how would i tell it which channel to create it to since idk what channels the server has?
You can get the guild using bot.get_guild(payload.guild_id)
Can't you just get the guild by the member?
Or is the member object different in payload
you know what are the channels using guild.channels
yes, how would i get it to pick a channel tho lol
nvm ill just use wait_for
if they really have member intents which is required for that purpose, why not just use the actual on_reaction_add event instead of raw reaction.
!d discord.RawReactionActionEvent.member
The member who added the reaction. Only available if event_type is REACTION_ADD and the reaction is inside a guild.
New in version 1.3.
We don't know
Ask the wise guy
i tried idk whats up with it
it mentiomed something to do with caching
not sure if thats relevant or not
"Unlike on_reaction_add(), this is called regardless of the state of the internal message cache." β
!e `print('bot dumb ong')
@feral lichen :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | `print('bot dumb ong')
003 | ^
004 | SyntaxError: invalid syntax
!e print('bot dumb ong')
@feral lichen :white_check_mark: Your eval job has completed with return code 0.
bot dumb ong
fr
wouldnt concern me tbh
eye-opening
Lol
!e
for a in range(0, 10):
print(f"my iq is {a}")
@feral lichen :white_check_mark: Your eval job has completed with return code 0.
001 | my iq is 0
002 | my iq is 1
003 | my iq is 2
004 | my iq is 3
005 | my iq is 4
006 | my iq is 5
007 | my iq is 6
008 | my iq is 7
009 | my iq is 8
010 | my iq is 9
Bro #bot-commands exists
code works now ig
help, when i set a default value to theme
@client.command
async def joke(ctx, theme="Any")
i get ```line 20, in get_joke
elif json["type"] == "single":
TypeError: 'module' object is not subscriptable
command()
i forgor that
Also what's yr dpy version?
wheres json from
Wait it's yr code
ye
ong or fr
Just saw... u have imported the json module
am ong
And doing smth like
import json
json["main"]
Huh?
oh wait im dum, my variable jsondata is similar to json and i have auto import so json got auto imported and i did not notice
im f/ with u lol
i wonder if theres any module that supports indexing
!d builtins
This module provides direct access to all βbuilt-inβ identifiers of Python; for
example, builtins.open is the full name for the built-in function
open(). See Built-in Functions and Built-in Constants for
documentation...
!e
import builtins
print(builtins["open"])```
@livid hinge :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | TypeError: 'module' object is not subscriptable
Huh weird
f
I remember doing that before π₯²
Prolly
it acts weird is all i remember
!e import builtins
@maiden fable :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | ModuleNotFoundError: No module named '__builtins__'
what r you trying to do?
this goes over the craziness http://mathamy.com/whats-the-deal-with-builtins-vs-builtin.html
that look like py2
i think the dict/module weirdness still happens in 3
Uh, thanks for killing my brain cells
but yeah that writeup is from python 2
__builtin__ was renamed to builtins in py3
so if __name__ == "__main__" then __builtins__ is the builtins module, but otherwise it's a dict
As an implementation detail, most modules have the name
__builtins__made available as part of their globals. The value of__builtins__is normally either this [builtins] module or the value of [the builtins] moduleβs__dict__attribute. Since this is an implementation detail, it may not be used by alternate implementations of Python.
definitely braincell-killing
Agreed
What's this?
when u import __builtins__ from a diff file, the list is produces is huge AF
how to send a message in a new embed when the main embed gets filled
In short, stop talking about it before u lose ur brain
make a new embed :p
it appears to be testing out behaviors of __builtins__
hm, why would that be
what's the best way of getting the bots ping (latency) ?
I've seen different ways and I just want to know the best way
bot.latency ...
Because Python just had a stroke
so I could use
@bot.command()
async def ping(ctx):
await ctx.send('Pong! {0}'.format(round(bot.latency, 1)))
Yea, sure
id prefer a f string though, but this works


reminds me of a meme but since we dont post those i'll just chuckle to myself
time to search the depths of hell
DMs π
What does this error mean
The second image is my json file
list indices must be int not str π³
So I replace str with int?
have you tried: Read the error
.id returns int so i dont think u need to, and the list in ur json is empty so you will get an indexerror
you are using the member id str as the index of the list
to do this you should use a dictionary that has as key the id of the member (str or int) and as a value the number of warn
so you can access the value using the key which would be the member id
What should I call the dict?
your dict should be in the json file
Ik
anyway I would use a database if I were you
What shall I call the dict?
as you want, warn_member_list?
Sure I guess
example of what your json file should look like
{
"710570210159099984" : 1
}
Thatβs what it will dump?
warns = {
"710570210159099984" : 1
}
Like that?
@client.command()
@commands.has_permissions(manage_messages = True)
async def status1(ctx):
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="over FLARELANDS"))
I want that bot send at messages when it change status how can I do that
Pls help anyone
Could you elaborate?
What?
You want to send message where?
I made a command which chane bot status i want that it send a message also
Into the same channel, right?
Ye
ctx.send
But it not worked
It does work π€·
Where do I add it
Means place
into your function after you change the presence
Ok
no, just a {}
I mean, json format structure always contains a root dictionary/array
which may contain keys, embedded dictionaries, lists, embedded lists in lists, etc.
It could contain an array too
yes that too
It's either object {} or an array []
but still json files arent really a good way of storing data, that is changed often
That's true, unless it's some sort of config file/static data
I would use yaml instead though
{} only
You also may make the string the user and : how much warns
Let it check if the user exist and add +1 to it everytime
I mean, sql is easy at the base level and sqlite is what I'd recommend since it easy to use (again, at the base level)
@formal basin I would recommend you to use a sql database instead, they're widely used in many applications, so it's a good opportunity to learn how to use them
You sure?
I like me some yaml
I'm sorry, why would you doubt when literally three persons said that?
Doesnβt work
wonderful, probably some other error
It means that there's no such key in dictionary
Maybe read how they work first if you're having troubles
Ohh I understand
File "main.py", line 165, in verify
veri = await client.wait_for('reaction_add', check = check, timeout = 30.0)
TypeError: check() takes 1 positional argument but 2 were given```
I believe timeout is the error, is there a fix?
Can you send code of check function?
def check(m):
return m.author == message.author and m.guild is None```
@honest laurel https://github.com/Rapptz/discord.py/issues/507 doesnt say this
What it doesn't say?
Look at check function this person has:
def check(react, user):
return react.message.author == ctx.message.author and ctx.message.channel == react.message.channel
so what am i suppose to do
Add second parameter to your check function
first would be reaction, second would be user
reaction, user = await client.wait_for('reaction_add', check=lambda reaction, user: reaction.emoji == 'π')
await user.send("π to you too!")```
like this
Yep
I still am not getting what I want
i want veri to be the emoji
veri = await client.wait_for('reaction_add', check = check, timeout = 30.0)```
and have a timeout
is there a way to get all the ids of users who reacted to a message without fetching?
I don't think that info would be in cache π€
oh ok
users = await message.reactions[0].users().flatten()
users.pop(users.index(client.user))```
oh let me try that
@honest laurel Help still
That would fetch users for single reaction though
@honest laurel
what's the flatten do ?
What?
What do i do
What exactly doesn't work?
I still am not getting what I want
i want veri to be the emoji
veri = await client.wait_for('reaction_add', check = check, timeout = 30.0)```
and have a timeout
!d discord.Message.reactions
Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
It would convert it into a list, it's an AsyncIterable by default
!d discord.Reaction.users
async for ... in users(*, limit=None, after=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") representing the users that have reacted to the message.
The `after` parameter must represent a member
and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
Changed in version 2.0: `limit` and `after` parameters are now keyword-only...
@honest laurel
You still didn't explain what doesn't work, i don't understand what you want
veri = await client.wait_for('reaction_add', check = check, timeout = 30.0)```
I want the value of **veri** to be the emoji.
This only checks for the emoji "π"
I want it to check for all emojis.
i don't understand what you want to do π
@commands.command()
async def tst(self, ctx, nab: Union[nextcord.Role, str]):
if nab.type == nextcord.Role:
await ctx.send('{0} is a role'.format(nab))
elif nab.type == str:
await ctx.send('{0} is a string'.format(nab))
else:
await ctx.send('error')
idk how to do it, can someone help me
I want it to check for ALL reactions and whatever reaction it gives output it to a variable.
nvm just realised i can use isinstance
It's a tuple
veri is a tuple of user and reaction objects
git clone the repo
Don't
pip install git+https://github.com/Rapptz/discord.py.git
Hello
I have got a linux vps, I installed everything on it, I uploaded my bot, but nothing works expect on_raw_reaction_add events.
There is no errors
nothing
@honest laurel py veri, user = await client.wait_for('reaction_add', check = lambda reaction, user: reaction.emoji == 'π', timeout = 30.0)
gives off "cannot assign to await expression"
What's the full error?
Show
veri, user = await client.wait_for('reaction_add', check = lambda reaction, user: reaction.emoji == 'π', timeout = 30.0)```
Error
Isnβt it wait for reaction
discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message_edit "discord.on_message_edit"),
if the message is not found in the internal message cache, then this
event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead...
And no need to add the on_
Send full traceback
This code is even useless for me
it only checks for "π"
I want it to check for every emoji
await message.delete(1)
TypeError: delete() takes 1 positional argument but 2 were given
why ?
delete doesn't take any arguments
I cant put delay as its argument
await message.delete(delay=1) so like this ?
Yes
is it the same as
await asyncio.sleep(1)
await message.sleep()
Yes
ok thank you
Nope
If it has a delay task would be created, it's not the same as calling asyncio.sleep and message.delete sequentially
Well, the crux is just that. It's gonna wait for a second (sleep) and then delete the message, just the implementation is via a task
It wouldn't block current task/coroutine though, unlike if you call asyncio.sleep
How do I check if a command is being invoked from another command or event
ctx.invoke
is it possible to use a bot to reboot the raspberry pi itβs running on?
when the monitor turns off cause the tv itβs on has an auto off thing it makes it impossible to really shut it down quickly and easily
Well, idrk but u will be able to shut it down via cli using os.system() or subprocesses
why after installing the new version discord.py have my events and simple commands stopped working?
Maybe api has changed?
@commands.command()
async def heist(self, ctx, role: nextcord.Role = None):
await ctx.send(f'{ctx.author.mention} will be hosting a heist')
def check(mes):
return ctx.author == self.bot.user
mes = await self.bot.wait_for('message', check=check)
print(mes.embed[0].title)
if "is starting a bank robbery" in mes.embeds[0].title:
no = 0
async for x in ctx.channel.history(limit=50):
if no != 1:
if x.content.lower().startswith('pls heist'):
user = x.mentions[0]
no = 1
await ctx.send(f"{user} is being heisted")
else:
return
mes = await self.bot.wait_for('message', check=check)
this waits for 1 message only and returns back if the conditions arent satisfied but i want it to wait for all messages sent until it gets timeout
and what does the event look like now in discord.py 2.0 ??
I would rewrite it as this:
@commands.command()
async def heist(self, ctx, role: nextcord.Role = None):
await ctx.send(f'{ctx.author.mention} will be hosting a heist')
def check(mes):
return ctx.author == self.bot.user
mes = await self.bot.wait_for('message', check=check)
print(mes.embed[0].title)
if "is starting a bank robbery" not in mes.embeds[0].title:
return
async for x in ctx.channel.history(limit=50):
if x.content.lower().startswith('pls heist'):
user = x.mentions[0]
await ctx.send(f"{user} is being heisted")
break
Not sure, send your code
@stray carbon
:hmm:
"break" oh
got it
thanks
Should work the same, less code and it's more readable imo
Are you sure your event handler doesn't work at all?
@commands.command()
async def heist(self, ctx, role: nextcord.Role = None):
await ctx.send(f'{ctx.author.mention} will be hosting a heist')
def check(mes):
return ctx.author == self.bot.user
mes = await self.bot.wait_for('message', check=check)
print(mes.embeds[0].title)
it didnt print the title
wait_for waits for one message only
and i was trying to do it for multiple messages
@bot.event
async def on_message(message):
if message.author == bot.user:
return
if message.content.startswith('Hello') | message.content.startswith('hello') | message.content.startswith('Hi') | message.content.startswith('hi') | message.content.startswith('ΠΡΠΈΠ²Π΅Ρ') | message.content.startswith('ΠΏΡΠΈΠ²Π΅Ρ') | message.content.startswith('ΠΏΡΠΈΠ²') | message.content.startswith('ΠΡΠΈΠ²'):
await message.channel.send(random.choice(["ΠΡΠΈΠ²Π΅Ρ","ΠΏΡΠΈΠ²Π΅Ρ","ΠΏΡΠΈΠ²","ΠΡΠΈΠ²","Hello","hello","Hi","hi","ΠΠΠΠ!!"]))
@bot.command()
async def hell(ctx):
await ctx.send("ΠΠΠΠ Π") ```
why in the new version discord.py it doesn't work at all!!?!?!??!!?
on_message makes your commands stop working
either you do bot.process_commands(message) at the end of on_message or replace @bot.event with @bot.listen()

i made a command group but the thing is when i use a?chelp
the bot sends the guide for it
but when i use a?chelp heist bot sends the guide of a?chelp and embed of a?chelp heist
@client.group()
async def chelp(ctx):
await ctx.send(embed=chelpEmbed)
@chelp.group()
async def heist(ctx):
await ctx.send(embed=heistEmbed)
code ^
@heady sluice
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "c:\Users\ToxicPenguin\Desktop\admin\server.py", line 20, in on_message
await bot.process_commands(message)
AttributeError: 'Bot' object has no attribute 'process_commands'```
ERROR
maybe it's outdated
use bot.listen
then replace @bot.event with @bot.listen() instead
its easier
Is there a way to fetch a users profile pic using his/her/theirs username
any help btw?
DOESN'T WORK WRONG WRONG
Note : ik about getting it using user id but I dont have user id I only have username
wym? send code
can't be

any help on this?
@slate swan
@bot.event
async def on_message(message):
await bot.process_commands(message)
if message.author == bot.user:
return
if message.content.startswith('Hello') | message.content.startswith('hello') | message.content.startswith('Hi') | message.content.startswith('hi') | message.content.startswith('ΠΡΠΈΠ²Π΅Ρ') | message.content.startswith('ΠΏΡΠΈΠ²Π΅Ρ') | message.content.startswith('ΠΏΡΠΈΠ²') | message.content.startswith('ΠΡΠΈΠ²'):
await message.channel.send(random.choice(["ΠΡΠΈΠ²Π΅Ρ","ΠΏΡΠΈΠ²Π΅Ρ","ΠΏΡΠΈΠ²","ΠΡΠΈΠ²","Hello","hello","Hi","hi","ΠΠΠΠ!!"]))
@bot.command()
async def hell(ctx):
await ctx.send("ΠΠΠΠ Π") ```
after installing d.py 2.0 does not work at all
haven't used groups yet
you did not replace @bot.event with @bot.listen()
u didnt addd bot.listen
Hell, it doesn't work with your @bot.listen()!!!!!!!!!!!!!
did u try
py bot.listen('on_message')
oh I found something in your code samandra
mhm?
you did chelp.group on heist instead of chelp.command
async with aiohttp.ClientSession(headers=self.headers) as session:
async with session.get(f'https://discord.com/api/v10/guilds/{guild.id}/audit-logs?limit=1&action_type=22', headers=self.headers) as r:
import json
auditlog = await r.json()
what is wrong
You should use or instead of |
Do your commands work?
he should use if message.content.lower().startswith() in ('hello', 'hi')
mah what does startswith return
what is wrong un
it is still the same
bool
both embeds are sent
yes
!d str.startswith
str.startswith(prefix[, start[, end]])```
Return `True` if string starts with the *prefix*, otherwise return `False`. *prefix* can also be a tuple of prefixes to look for. With optional *start*, test string beginning at that position. With optional *end*, stop comparing string at that position.
.
Donβt work
yeah passed list in startswith
@slate swan @honest laurel @heady sluice
@bot.listen('on_message')
async def on_message(message):
if message.author == bot.user:
return
if message.content.startswith('Hello'):
await message.channel.send(random.choice(["ΠΡΠΈΠ²Π΅Ρ","ΠΏΡΠΈΠ²Π΅Ρ","ΠΏΡΠΈΠ²","ΠΡΠΈΠ²","Hello","hello","Hi","hi","ΠΠΠΠ!!"]))```
it doesn 't work !
Π½Π΅ ΡΠ°Π±ΠΎΡΠ°Π΅Ρ!
ignorance
give to me the full error
Ok 1 sec
as I said the best thing would be to use a database
you mean the commands don't work or what you want to do here?
I will help them in dm's i think they don't speak english well π
you might need message_content intents
I say no commands, no events don't work!!!!
ΠΠ ΠΊΠΎΠΌΠ°Π½Π΄Ρ Π½Π΅ ΠΈΠ²Π΅Π½ΡΡ Π½Π΅ ΡΠ°Π±ΠΎΡΠ°ΡΡ!!!!
@heady sluice 
veri, user = await client.wait_for('reaction_add', check = react_check, timeout = 30.0)```
gives off
File "main.py", line 365, in on_raw_reaction_add
if (payload.member.id == 973196740310237234):
AttributeError: 'NoneType' object has no attribute 'id'```
@heady sluice
async with aiohttp.ClientSession(headers=self.headers) as session:
async with session.get(f'https://discord.com/api/v10/guilds/{guild.id}/audit-logs?limit=1&action_type=22', headers=self.headers) as r:
import json
auditlog = await r.json()```
how to solve
well that sucks
thank you
help me too please
you could wait for multiple messages in a while loop
veri, user = await client.wait_for('reaction_add', check = react_check, timeout = 30.0)```
gives off
File "main.py", line 365, in on_raw_reaction_add
if (payload.member.id == 973196740310237234):
AttributeError: 'NoneType' object has no attribute 'id'```
ignorance i got no help
or an event
from shero bot support?
@heady sluice do you really know the language or are you just writing bullshit ?
Imma ignore you this time
your error doesn't match your code, could you send your on_raw_reaction_add event?
π ye
example?
Believe me, I know. I'm confused too.
There's no on_raw_reaction_add event in my code.
uh
error shows it's in your main.py
line 365
!d discord.RawReactionActionEvent.member seems to be None for you
The member who added the reaction. Only available if event_type is REACTION_ADD and the reaction is inside a guild.
New in version 1.3.
send the json file
do you want to wait for messages in in a certain time, or for a certain amount of messages?
and your script
Certain time
maybe no while loop is needed, wait
do you know how to use the datetime module?
gg json
is that replit?
just use the auto thing
dont edit thing if you dont know how
I was thinking you return False in your check if that time isn't reached yet
I do a bit
anyway I ridicule it, you should use a database
with open('warns.json', 'r') as f:
warns = json.load(f)
warns[str(member.id)] += 1
with open('warns.json', 'w') as f:
json.dump(warns, f)
def remove_warn(ctx, member: discord.Member, amount: int):
with open('warns.json', 'r') as f:
warns = json.load(f)
warns[str(member.id)] -= amount
with open('warns.json', 'w') as f:
json.dump(warns, f)
def warns_check(member: discord.Member):
with open('warns.json', 'r') as f:
warns = json.load(f)
warns[str(member.id)]
return warns
@slash.slash(name="warn", description="admin only")
@commands.has_permissions(kick_members=True)
async def warn(ctx, member: discord.Member, *, reason):
channel = client.get_channel(944547350448308244)
save_warn(ctx, member)
dm = await client.fetch_user(member.id)
warns = warns_check(member)
em=discord.Embed(title="Warning", description=(f"{member.name} has been warned, warning number {warns}", f"by {ctx.author.name} Reason: {reason}"))
embed=discord.Embed(title="Warning", description=f"warning number {warns}. By {ctx.author.name}\nReason: {reason}.")
await dm.send(embed=embed)
await channel.send(embed=em)
@slash.slash(name="warnings", description="admin only")
@commands.has_permissions(kick_members=True)
async def warnings(ctx, member: discord.Member):
warns = warns_check(member)
await ctx.send(f"{member.name} has {warns} warnings.") ```
no idea how to limit the while True loop using datetime
messages = []
def check(message):
if message.channel.id == some_id:
messages.append(message)
if time > end_of_time:
return True
return False
```smth like what I was thinking
with open('warns.json', 'r') as f:
warns = json.load(f)
warns[str(member.id)] += 1
with open('warns.json', 'w') as f:
json.dump(warns, f)
def remove_warn(ctx, member: discord.Member, amount: int):
with open('warns.json', 'r') as f:
warns = json.load(f)
warns[str(member.id)] -= amount
with open('warns.json', 'w') as f:
json.dump(warns, f)
def warns_check(member: discord.Member):
with open('warns.json', 'r') as f:
warns = json.load(f)
warns[str(member.id)]
return warns
@slash.slash(name="warn", description="admin only")
@commands.has_permissions(kick_members=True)
async def warn(ctx, member: discord.Member, *, reason):
channel = client.get_channel(944547350448308244)
save_warn(ctx, member)
dm = await client.fetch_user(member.id)
warns = warns_check(member)
em=discord.Embed(title="Warning", description=(f"{member.name} has been warned, warning number {warns}", f"by {ctx.author.name} Reason: {reason}"))
embed=discord.Embed(title="Warning", description=f"warning number {warns}. By {ctx.author.name}\nReason: {reason}.")
await dm.send(embed=embed)
await channel.send(embed=em)
@slash.slash(name="warnings", description="admin only")
@commands.has_permissions(kick_members=True)
async def warnings(ctx, member: discord.Member):
warns = warns_check(member)
await ctx.send(f"{member.name} has {warns} warnings.") ```
i realised you can't because it would depend on when the last message is sent
there are big mistakes
it would be stuck on a wait_for
:hmm:
this is what I thought