#discord-bots
1 messages · Page 838 of 1
just confused as some editors just convert tabs as spaces
Yea, but that doesn't mean tabs == spaces

yeah
if you accidentally used tabs in a bunch of code that uses spaces couldn't you fix it in like 5 seconds with search and replace all
Depends on your IDE, probably
class Tabs(Spaces):
def __init__(self):
super().__init__()
I'm sure some searches would return spaces for tabs
probably
!e ```py
class Tabs:
...
class Spaces(Tabs):
...
print(Tabs == Spaces)
print(Tabs() == Spaces())
yeah Ik
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
001 | False
002 | False
Does black turn tabs in to spaces?
lol
Black turns tabs into spaces iirc
There exists a seperate package for black with tabs
Yea, checked it does
wth
need helper role i think
!e
class Tabs:
def __init__(self):
self.point_in_vsc = "Indents"
class Spaces(Tabs):
def __init__(self):
self.point_in_vsc = "Indents"
print(Tabs.point_in_vsc == Spaces.point_in_vsc)
@cold sonnet :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 9, in <module>
003 | AttributeError: type object 'Tabs' has no attribute 'point_in_vsc'
No
oh it’s just general
I suck at this
!e
class Tabs:
def __init__(self):
self.point_in_vsc = "Indents"
class Spaces(Tabs):
def __init__(self):
self.point_in_vsc = "Indents"
print(Tabs().point_in_vsc == Spaces().point_in_vsc)
@final iron :white_check_mark: Your eval job has completed with return code 0.
True
👍🏿
!e
x = 3
if x == 3:
print('.')
if x == 3:
print('..')
can’t you use super().__init__ for that?
@manic wing :white_check_mark: Your eval job has completed with return code 0.
001 | .
002 | ..
¯_(ツ)_/¯

what are the rules for splitting code into seperate modules? The first project i completed ended up being one file of around 2500 lines
you mean cogs?
there are no rules per se
^
just try and categorize your commands
so help commands can automate them
its in your best interest
I generally put everything in srcfolder, and split everything up
one folder for utils, helpers, etc
you choose where the line is, its all personal preferance really
i mean more in general for python

As @manic wing said there are no specific rules
but if you want to show something is a module or lib prolly put an empty __init__.py in there
just dont have too many classes and functions in a file and you'll be cool
you can also use __all__ in __init__.py files (or any file, it is just generally used in __init__.py) to control wild card imports
!star-imports
Star / Wildcard imports
Wildcard imports are import statements in the form from <module_name> import *. What imports like these do is that they import everything [1] from the module into the current module's namespace [2]. This allows you to use names defined in the imported module without prefixing the module's name.
Example:
>>> from math import *
>>> sin(pi / 2)
1.0
This is discouraged, for various reasons:
Example:
>>> from custom_sin import sin
>>> from math import *
>>> sin(pi / 2) # uses sin from math rather than your custom sin
• Potential namespace collision. Names defined from a previous import might get shadowed by a wildcard import.
• Causes ambiguity. From the example, it is unclear which sin function is actually being used. From the Zen of Python [3]: Explicit is better than implicit.
• Makes import order significant, which they shouldn't. Certain IDE's sort import functionality may end up breaking code due to namespace collision.
How should you import?
• Import the module under the module's namespace (Only import the name of the module, and names defined in the module can be used by prefixing the module's name)
>>> import math
>>> math.sin(math.pi / 2)
• Explicitly import certain names from the module
>>> from math import sin, pi
>>> sin(pi / 2)
Conclusion: Namespaces are one honking great idea -- let's do more of those! [3]
[1] If the module defines the variable __all__, the names defined in __all__ will get imported by the wildcard import, otherwise all the names in the module get imported (except for names with a leading underscore)
[2] Namespaces and scopes
[3] Zen of Python
Can somebody send me an invite link for the discord.py official server?
i have 46 functions in the current project im working on all in one file but idk where to split it
Hey guys, im coding my discord bot right now, and for some reason i just got this error
disnake.ext.commands.errors.ExtensionFailed: Extension 'cogs.setup' raised an error: RecursionError: maximum recursion depth exceeded
well name some of the functions and ill tell you where you should put them
All my homies love the namespace file 😼
how do i get a user by id then private dm them?
its never happened before, and it happens on a specfic cog
from traceback import print_exception
import random
import requests
import json
import disnake
from disnake import Embed
from disnake.ext import commands
from pycoingecko import CoinGeckoAPI
from dataclasses import dataclass
from ssl import Purpose
from etherscan import Etherscan
from yaml import safe_load
import time
import asyncio
from typing import Optional
from sqlitedict import SqliteDict
from modules.database import Server
with open('config.yml') as f: config: dict = safe_load(f)
class setup(commands.Cog):
def __init__(self, client):
self.client = client
print(1)
def setup(client):
client.add_cog(setup(client))```
You can only dm is the DMChannel is open
!d discord.DMChannel
class discord.DMChannel```
Represents a Discord direct message channel.
x == y Checks if two channels are equal.
x != y Checks if two channels are not equal.
hash(x) Returns the channel’s hash.
str(x) Returns a string representation of the channel
kk how would i get the user by discord id?
get_user
lol 🗿
biggest function is draw_img and it links to maths stuff to randomly generate tiles in specific ways and then there's stuff that actually draws various tiles on conditions
@slim ibex @manic wing you guys know a solution for
disnake.ext.commands.errors.ExtensionFailed: Extension 'cogs.setup' raised an error: RecursionError: maximum recursion depth exceeded
dont ping random people
if you use it in multiple places, put it in utils/draw.py
Recursion 👁️ 👁️ , are you like trying to load your extension inside of setup
That would just be a loop^
rename your cog to something different
your bot calls the setup function
so its trying to call both and its having a seizure
- just name errors
lmao
member = message.guild.get_member(first_word)
i get this error: ```
Ignoring exception in on_message
Traceback (most recent call last):
File "/home/runner/BaconHubAutoPurchaseHandler/venv/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 28, in on_message
if user:
NameError: name 'user' is not defined
the first_word var is the uers's id
show the whole function
@client.event
async def on_message(message):
print(message.channel.id)
if message.channel.id == 943253794819555368:
first_word = message.content.split()[0]
member = message.guild.get_member(first_word)
print(member)
if user:
print("lolll")
used is not defined as a variable or anything
what are you trying to do
get user by id
for what purpose?
a whitelist automation im making
if message.author.id == <some_id>:
oioh shit wait i think i just fixed it
prolly shouldn’t do it in an on message event only?
i see
its cuz another bot is sending messages to a private channel for this bot to read
so that capicalizatins always the same
thank you
nvm
see, the first print prints out the id but the get user by id part returns none
@client.event
async def on_message(message):
print(message.channel.id)
if message.channel.id == 943253794819555368:
first_word = message.content.split()[0]
member = message.guild.get_member(first_word)
print(member)
new code
you are getting the member from the message content??
don’t think this is the most efficient way to do what you want
trust me like i said, itll work out
cuz im using a bot i didnt make to send the messages so i cant modify the other bot
this turned on?
are you wanting to get the message author or just a random user
s o i have a tebex webstore that sends the user id to a channel and cuz its not my bot i cant modify is so its sending the user id of the person that purchased the product then im having my bot read the message
and the first_word variable is the purchasers user id
wouldn't your bot not be able to fetch them because it's not in the same guild?
no, the user you're fetching
but like you are trying to get a member with message.content
they are in the guild
they are the owner of the guild
im trying to get a member by id but the id is a variable
that i called first_word
only thing i can think of is that you're missing member intents, you could try fetch user
await client.fetch_user(id)
and im not ab to loop through all members to check if their user id matches cuz thatll lag too much
that worked
thx, i finally figured it out
yall helped me
yeah it was probably members intent you were missing, np
np
this is the current bot im working on
if you need to identify the type of file before sending it then you'd probably need to use twitter api
another way i could see doing it, is posting the link which discord will auto embed, then you can get the content of that message which should have the extension
possibly
hey can anyone help me to make stop command?
@client.command()
@commands.has_permissions(administrator=True)
async def dmSpam(ctx, user_id=None, *, args=None):
if ctx.message.author.id == 404354878035722240:
await ctx.send("spierdalaj")
else:
if user_id != None and args != None:
try:
while True:
target = await client.fetch_user(user_id)
await target.send(args)
await ctx.channel.send("'" + args + "' wyslano do: " + target.name)
except:
await ctx.channel.send("Nie mozna wyslac wiadomosci")
looks interesting
a stop command? well what condition do you want to stop the loop
but very confusing
What method can be used to remove a server role using a bot?
too much stuff to interact with on each screen?
i just want to make ;stop and bot stops spamming
i've been trying to keep it to 3 lines but
way too much
to much information to process
try and make it more visually appealing and easy to use maybe
target = await client.fetch_user(user_id)
await target.send(args)
await ctx.channel.send("'" + args + "' wyslano do: " + target.name)```
This is an infinite loop
it flicks between so many different pages
idk about too much info to process aside from all the buttons
seems like less than a regular game, just energy and depth for gui and then interactions
I could possibly move some stuff to later levels to slow the learning curve, like at the start i made it so you spawn with an extra energy thing which makes the use item bar appear
but if you have no items then it doesn't show up, so i could move that later as a guaranteed item after you've dug a certain depth for example
dont do this
- rate limits
- ctx gets the channel were the context was invoke so no need for the channel attr
- f strings are a thing
4.youre making request in a loop which will raise a 429 by the api since youve been making so much api calls in a short amount of time
we might not want to help someone who has a function called dmspam now that i think about it 🤔
Why do you fetch user in each iteration
stop replying to me, it's not my code 😤
theres nothing good about such a feature and even if you sleep each time youre sending a message the discord api has dynamic ratelimits so it wouldnt be very good on the client side
I’ m sorry I didn’t know
?
limit=None this should not be None
add a default value of 1 to limit
so it will never raise such an error
if you want but i recommend to make it 1 so you will always know the value of it.
code?
and why add a value to limit when you can add a defualt value in params?
and it wont work as you set a value to limit in the params of the method you should do it in the methods parameters
def method(limit: int = 1) -> None:
...
here limit is expected to be an int and has a default value of 1 which the method returns None
Is anyone else feeling stuck with their bots?
why?
the error says it.
I know how to but I just feel sort of down about it
It’s not true tho
im feeling procrastinaty with mine. Got pretty far with it and decided to rewrite a bunch of code to be more efficient and im half way through with a non working bot again
how can i make it so that if a member goes offline a role will be given to them and when theyre online it will be removed?
I've gotten mine up but it doesn't have any commands yet. I have like empty cogs already too. I just feel unmotivated, I guess
i believe that u need on_member_update event
Nah I just start on an idea and then it seems pointless and scrap it
gotta push through the pointless feeling
!d discord.ext.commands.on_member_update
No documentation found for the requested symbol.
everythin pointless
Yea ig
the pointless feeling always appears for me about half way through a project and by the time im at 3/4 excited comes back
on_member_update(member, before, after)
thats false
its just before and after
Im not sure what?
Member is also a possibility
You're right. I gotta push through. Thanks guys. Am gonna start up my terminal
Isn't it?
!d discord.on_member_update
discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") updates their profile.
This is called when one or more of the following things change:
• nickname
• roles
• pending...
you can do it cloud
2 params lol
no, its just before and after, before and after is itself member
@fervent shard
Ah mb
Yh i see it now. Don't have my code with me atm
Me neither
weird how it doesnt take that param
member param would be same as after
Yh indeed
after and before are member objs yes
I wasn't thinking, should've thought more
Wdym
Ik that feeling
you cant learn everything lol
When u make a stupid mistake😂
Sounds so relatable
async def on_message(message):
if message.author.id == 897789854472106004 and message.content == "on_member_update(member, before, after)":
for user in the_whole_of_discord:
await message.send(f"{user.name}: you wrong")```
a bot can't cache all users in the api
😤 it can sure try
youll need more than 2tb of ram
I dont think thats how it works 😂
sounds like a challenge to me
Caching entire discord db
to your wallet
why does my bank have 0$ on it?
is there an event that checks the user's presence
like on_member_presence stuff like ths
why would theyre be an event
actually i just forgot the event
there is one that checks the user's status(bio)
!d discord.Member.status
property status: discord.enums.Status```
The member’s overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") instead.
In versions less than v2.0 it is on_member_update, you can check the presences to see if they updated
And in versions v2.0+ they have on_presence_update
btw
on_member_update allows me to check the user's bio aka status
like if they put something in their status they'll get something
whatever
!d discord.on_member_update
discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") updates their profile.
This is called when one or more of the following things change:
• nickname
• roles
• pending...
if after.member.status == something idk what:
they online```
or is it just after.status idk
i think it's just after.status
what exactly you want to check
hello i make talking ben dog
ben_responses = ["yes", "no", "ben", "haha", "eugh"]
@bot.command(name="ask")
async def ask(ctx: commands.Context):
await ctx.send(random.choice(ben_responses))
why is it repeating more and more responses?
after.member?
after and before return member objs?
nvm
async def discord.on_member_update?
This does not look right,
look im very tired
The docs only show you the parameters it takes. You need to decorate a function with the event or listen() decorator with the event name
that being on_member_update
are you running multiple instances of your bot?
ohhh
async def on_member_update(before, after):
if after.status == "online":
they online
mmm but i want to get the member's custom status
Oh, that status. Well you'd use the same event anyways, on_member_update, they give you the before and after edit of the Member, just check their activity attribute and check if it's a custom one
!d discord.CustomActivity
class discord.CustomActivity(name, *, emoji=None, **extra)```
Represents a Custom activity from Discord.
x == y Checks if two activities are equal.
x != y Checks if two activities are not equal.
hash(x) Returns the activity’s hash.
str(x) Returns the custom status text.
New in version 1.3.
!d discord.Member.activity
property activity: Optional[Union[discord.activity.Activity, discord.activity.Game, discord.activity.CustomActivity, discord.activity.Streaming, discord.activity.Spotify]]```
Returns the primary activity the user is currently doing. Could be `None` if no activity is being done.
Note
Due to a Discord API limitation, this may be `None` if the user is listening to a song on Spotify with a title longer than 128 characters. See [GH-1738](https://github.com/Rapptz/discord.py/issues/1738) for more information.
Note
A user may have multiple activities, these can be accessed under [`activities`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.activities "discord.Member.activities").
tnx ^^
is there a consistent font for discord across all devices?
How to call a command from another file?
iirc yes
you cant you use cogs
And with cogs it is possible somehow?
yes cogs are exts which are in different files
@rare saddle https://tutorial.vcokltfre.dev/tutorial/05-cogs/
Cogs are a very important part of discord.py which allow you to organise your commands into groups - not to be confused with actual command groups, which will be explained later in the tutorial.
I'm trying to think of a non-dumb way to do this. It generates a certain amount of dashes and spaces after whatever text to make each dashed line end at the same place.
character_size = {
"lij|' ": -13,
"![]fI.,:;/\\t": 0,
'`-(){}r"': 10,
"*^zcsJkvxy": 35,
"aebdhnopqug#$L+<>=?_~FZT": 45,
"SBPEAKVXY&UwNRCHD": 62,
"QGOMm%W@": 85,
}
def get_dashes(st):
size, dashes = 0, ""
for s in st:
for chs in character_size:
if s in chs:
size += character_size[chs]
break
size += 50
while size < 2000:
dashes += "-"
size += 60
if size < 2000:
dashes += " "
size += 37
return dashes```
What does it Rate limit?
I may not quite understand, but there I did not find an example of importing a command from one file to another
For some reason Discord doesn't register my Slash commands globally, it worked locally, it doesn't even let me sync_commands_debug, does somebody know what the problem might be?
!e
import random
print(f"lol{'_' * random.randint(1, 10)}lol")
😤
@slate swan :white_check_mark: Your eval job has completed with return code 0.
lol_______lol
you dont you load them with
!d discord.ext.commands.Bot.load_extension
load_extension(name, *, package=None)```
Loads an extension.
An extension is a python module that contains commands, cogs, or listeners.
An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.
which youll need to make a global setup
my slash commands won't go through, can somebody guess the reason
its all in the tutorial
wdym
The slash commands worked locally, but as soon as I made them global, they wont show on the server
You did not understand. I already use cogs
it takes 1 hour to load all of them in all servers
It's been 2 hours
they take about an hour to register globally
does the bot have applications.command parameter while you invited it?
cogs are the only way
I have an addblack command that I need to import from one file to another
If the commands worked in local, does it matter if the applications.commands is set?
its application.commands and its a scope
yes
cog is the only way
I'll check!
I already use them
What does To upser: Slash commands mean though?
depends on what invite they used and if the scope was on
!e
character_size = {
"lij|' ": -13,
"![]fI.,:;/\\t": 0,
'`-(){}r"': 10,
"*^zcsJkvxy": 35,
"aebdhnopqug#$L+<>=?_~FZT": 45,
"SBPEAKVXY&UwNRCHD": 62,
"QGOMm%W@": 85,
}
def get_dashes(st):
size, dashes = 0, ""
for s in st:
for chs in character_size:
if s in chs:
size += character_size[chs]
break
size += 50
while size < 2000:
dashes += "-"
size += 60
if size < 2000:
dashes += " "
size += 37
return dashes
test = ""
for i in ["random", "Text lengths", "with", "dashes"]:
test += f"{i} {get_dashes(i)}"
print(test)
@dull terrace :white_check_mark: Your eval job has completed with return code 0.
random - - - - - - - - - - - - - - - Text lengths - - - - - - - - - - - -with - - - - - - - - - - - - - - - - - -dashes - - - - - - - - - - - - - - -
But I don't know how to import this command
oop should have been new lines
Fuck
#bot-commands
From one cog to another
you dont commands should be in a subclass of the Cog class
!e
character_size = {
"lij|' ": -13,
"![]fI.,:;/\\t": 0,
'`-(){}r"': 10,
"*^zcsJkvxy": 35,
"aebdhnopqug#$L+<>=?_~FZT": 45,
"SBPEAKVXY&UwNRCHD": 62,
"QGOMm%W@": 85,
}
def get_dashes(st):
size, dashes = 0, ""
for s in st:
for chs in character_size:
if s in chs:
size += character_size[chs]
break
size += 50
while size < 2000:
dashes += "-"
size += 60
if size < 2000:
dashes += " "
size += 37
return dashes
test = ""
for i in ["random", "Text lengths", "with", "dashes"]:
test += f"{i} {get_dashes(i)}\n"
print(test)```
@dull terrace :white_check_mark: Your eval job has completed with return code 0.
001 | random - - - - - - - - - - - - - - -
002 | Text lengths - - - - - - - - - - - -
003 | with - - - - - - - - - - - - - - - - - -
004 | dashes - - - - - - - - - - - - - - -
the with one is longer 😤
that is so overcomplicated
It still doesn't work man :(((
2 liner
@tidal hawk
but that doesn't look neat, i want the same length so i can add info after
invited the bot with applications.Comamnds on for sure
how does that not look neat?
Only thing what it gaves me ->
lib?
disnake
you can check in there help channels
i doubt its a problem with the lib
but they know more about the lib
uhm
item - - - - some thing here
another item - - - - - - - another thing here related to item
x - - something
VS.
item - - - - - - - - - - - - -some thing here
another item - - - - - - - another thing here related to item
x - - - - - - - - - - - - - - - something
ah well that's something else
there was some reason i ruled out using fields for it but i can't remember why
Okay!
why so many dashes why
!e ```py
first = ["first", "second", "third"]
second = ["fourth", "fifth", "sixth"]
for f, s in zip(first, second):
print(f"{f:10s} {s}")
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
001 | first fourth
002 | second fifth
003 | third sixth
what does zip even do?
!d zip
zip(*iterables, strict=False)```
Iterate over several iterables in parallel, producing tuples with an item from each one.
Example:
```py
>>> for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice']):
... print(item)
...
(1, 'sugar')
(2, 'spice')
(3, 'everything nice')
```...
ic
I don't see 💀
poor you i guess
enumerate(zip()) moment
Oh woops I did something wrong here so the first isn't aligned
I'll fix that rq
!e ```py
first = ["first", "second", "third"]
second = ["fourth", "fifth", "sixth"]
for f, s in zip(first, second):
print(f"{f:10s}{s}")
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
001 | first fourth
002 | second fifth
003 | third sixth
how are they not aligned
The codeblock has lines
!e
names = ['Alice', 'Bob', 'Charlie']
ages = [24, 50, 18]
for i, (name, age) in enumerate(zip(names, ages)):
print(i, name, age)
@slim ibex :white_check_mark: Your eval job has completed with return code 0.
001 | 0 Alice 24
002 | 1 Bob 50
003 | 2 Charlie 18
I'm assuming it's that
they look aligned to me
same
lol the font
ikr
😔 they aren't aligned for me and it's driving me crazy
sucks for you
jk jk
???
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'create_dm'``````py @bot.command(aliases=['t']) async def ticket (ctx: commands.Context, member: discord.Member = None): channel = await member.create_dm() await channel.send("hi this is a test")
member is None
your member is none
oh right-
NoneType doesnt have such an attr since member is None
No need to manually create the dm
if you want it to be a member or the author just make member have a value of author
You can just call await member.send(...)
that as well its kinda useless
!e
chr_sizes = {' ': 91, "'.": 128, 'i': 132, '|': 134, ':': 138, '!I': 145, 'j;': 146, 'l': 147, ',': 155, 'f': 162, '[]': 164, 't': 168, 's': 213, '<>': 222, 'z': 228, 'c': 231, '*': 238, 'e': 239, 'a': 241, '~': 244, '?': 245, '/o': 246, '\\': 251, 'g': 252, 'b': 253, 'dpq': 254, 'k': 255, 'nu': 256, 'yh': 257, 'v': 260, 'x': 262, '=': 264, 'L': 269, 'S': 282, '+': 283, '$': 285, 'F': 288, 'C': 291, 'T': 292, 'J': 293, 'E': 294, '_': 296, 'Z': 302, 'P': 309, 'G': 311, 'B': 312, 'D': 318, '#': 324, '^K': 326, 'R': 328, 'AXQO': 332, 'U': 334, 'VYNH': 338, '&': 345, 'm': 367, '%': 370, 'w': 377, '@': 380, 'M': 384, 'W': 458}
def get_dashes(st):
size, dashes = 0, ""
for s in st:
for chs in chr_sizes:
if s in chs:
size += chr_sizes[chs]
break
while size < 3000:
dashes += "-"
size += 60
if size < 3000:
dashes += " "
size += 37
return dashes
test = ""
for i in ["random", "Text lengths", "with", "dashes"]:
test += f"{i} {get_dashes(i)}\n"
print(test)```
@dull terrace :white_check_mark: Your eval job has completed with return code 0.
001 | random - - - - - - - - - - - - - - - - -
002 | Text lengths - - - - -
003 | with - - - - - - - - - - - - - - - - - - - - - -
004 | dashes - - - - - - - - - - - - - - - - -
god dammit

W | |
idk the sizes look right, W seems over 4x larger than space
oh i didn't update the - and space size lower down derp
!e ```py
first = ["first", "second", "third"]
second = ["fourth", "fifth", "sixth"]
for foo, bar in zip(first, second):
print(f"{foo.ljust(10, '-')}{bar}")
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
001 | first-----fourth
002 | second----fifth
003 | third-----sixth
pov: you should touch grass
They aren't aligned on my screen, but I am assuming they are 😩
For some reason my discord client want's to give me OCD
they are lol
i think they're called context menus
slash commands
arent context menus dropdowns lol
googled
guess theyres a difference lol
they are application commands
yes
but not slash commands
Hello, is there a way to get the avatar url in jpg instead of png?
youre welcome
Just remembered I need to add context menu commands to my wrapper
😔, no more procrastination after 2day
Member first or Slash commands 😼
power just went out for a sec, stupid storm
does anyone actually use context menus
i never even think to right click a bot pfp
It would be good for things like translating a message
As context menus are also there for messages
member ofc
That's no fun though 😔
imagine not having basic models
It's cause they are so tedious to add, albeit easy
and btw why make a discord api wrapper after theyres so much forks etc?
do you guys have any bots out right now?
Used to
what happened?
I archived the project and deleted the repo after my discord account got hacked
But I still have to bots source code
why not make a v2?
I don't like forks, I don't like discord.py's semantics
Thought about it
get_channel is O(n) 😔
i see
I actually was but the other contributor got hacked I think
how
Im actually making a bot for my friends new server,
do it yourself lol
Because that's how danny decided to do it, instead of having an O(1) cache
but I’m waiting for rin 🗿
bruh
i've only made 1 discord bot so far and it was basically my first serious python project, code is an absolute mess in some places
what bots?
priv bots lol
oh okay
Hello, is there a way to get the avatar url in jpg instead of png?
the url in png?
would probably have to convert it
thanks
yea
What’s the file structure
How to import addblack command from blacklist.py file to modmail.py file?
Files in the same directory
^
from .filename import function?
hopefully there is an __init__.py in your directory
does not work
Yes, but it's empty
I have never created such a file before
Sorry I gtg, someone else gotta help you
But I’d put an __init__.py file in each directory
Okay, thanks
can someone help me with something rq
what would I change to make profile_name into “username”
Send your code
Make the param username
ok
Hey @hollow urchin!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
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 sent in dms
yes
See profile_name in the function params?
how do I pass an async check to bot.wait_for()?
which line
The function params...
!d discord.ext.commands.Bot.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
yeah async check how
I don't code I just need help changing that
🗿
🗿🗿
🗿🗿🗿🗿🗿🗿🗿🗿🗿🗿🗿🗿
stop
anyways can you help
No
you may leave
bruh
💀
They asked the question 💀
we dont spoonfeed here if you cant do it yourself leave
panda
I might've found a behaved person
how do you pass an async check to a wait_for
I change that?
ill do my own research for once
Change that to whatever you want it to be
ai
In the case you provided it should be username
like any coro?
yes
What zilo is trying to say, this is pretty basic, think about it. Just change all the profile_name in the code to username
ctx.year = await self.bot.wait_for("message", check=check, timeout=60.0)
async def check(m: str):
ai bro
check= await check()
wouldnt that work?
You can just pass in the function right? Since it is async and awaiting you don't need a second await.
It’s a coroutine so it’s already awaiting yeah
no
I got the traceback allocation error from the source code
Do make sure the function is defined before assigning the check.
if you have 2 coros in a line you have to wait both of them
What is the error?
lemme do it again so the error comes out
C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\disnake\ext\commands\common_bot_base.py:106: RuntimeWarning: coroutine 'Birthday.birth.<locals>.check' was never awaited
super().dispatch(event_name, *args, **kwargs) # type: ignore
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
await the coro lol
wdym does check call the func?
no, you just pass in the function
bro what
meant source code
nah youre tripping
guess it's time for in-source code error handling
Hmm can't you create a async task loop inside that function.
!d asyncio.create_task
asyncio.create_task(coro, *, name=None)```
Wrap the *coro* [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine) into a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task") and schedule its execution. Return the Task object.
If *name* is not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.set_name "asyncio.Task.set_name").
The task is executed in the loop returned by [`get_running_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop "asyncio.get_running_loop"), [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError "RuntimeError") is raised if there is no running loop in current thread.
This function has been **added in Python 3.7**. Prior to Python 3.7, the low-level [`asyncio.ensure_future()`](https://docs.python.org/3/library/asyncio-future.html#asyncio.ensure_future "asyncio.ensure_future") function can be used instead...
def leave(error):
coro = vc.disconnect()
fut = asyncio.run_coroutine_threadsafe(coro, bot.loop)
try:
fut.result()
except:
pass
this'd work too
What do you even need to await inside a check?
I guess
ctx.send
Why would you need a send there.
why not

The more I do stuff on my own I realize how sped I am.
ey don't question my logic, question how I'm doing it
how would i use a hex code to colour an embed?
you use the color kwarg and use the prefix 0x
!d discord.Embed
class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
You could've just added an error handler 👁️ 👁️
Ignoring exception in command wordle:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 73, in wordle
rewordle.play(WordleSolver())
TypeError: play() missing 1 required positional argument: 'solver'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: play() missing 1 required positional argument: 'solver'
if that line gets the await error, it awaits the check
Ay ideas?
the traceback says it all
ret = await coro(*args, **kwargs)?
!e
def function(argument):
print(argument)
function()
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 4, in <module>
003 | TypeError: function() missing 1 required positional argument: 'argument'
thanks
whats this?
you're welcome
an example on the error
what am I doing wrong?
nah i dont
super().dispatch(event_name, *args, **kwargs) # type: ignore
k well I don't know what this means but we're getting there
oh
thats not default
ik
defualt is dark grey
like to make that blue into the colour next to it
to make it invisible / transparent
doubt you can
the mobile and pc clients both have different color of grays in the themes
got it!
The hex code is 0x36393F for the discord's background
BetterDiscord users
Like themes?
yes
We're not really allowed to suggest betterdiscord here since they violate tos
not secure at all
IP grabbers everywhere
to have custom or pirated clients
This function returns the first event that meets the requirements...
it's a scam
or I'm just dumb
@commands.command()
async def birth(self, ctx):
def check(m: disnake.Message):
content = m.content
if content.isnumeric():
if int(content) < 2022 and int(content) > 1980:
return True
else:
coro = ctx.send("**Az IGAZI születési éved?**")
fut = asyncio.run_coroutine_threadsafe(coro, self.bot.loop)
try:
fut.result()
except Exception as e:
raise e
return False
```first event that returned False shut the whole thing down
👁️ 👁️ , your check function is inside of a coroutine one
Just turn it into a coroutine function and await it inside of birth
now what
now await the ctx.send instead of whatever the hell that is
why not
cuz how do I pass it to wait_for
Ah your passing this to wait_for
Ahha moment
idrk what to do
if I type like 2005 it succeeds
if I type 1960 nothing happens
Do you get any errors at all
I would just get rid of the future.result stuff, just do something like self.bot.loop.create_task(coro)
Add that to the else statement
sure
and make sure to return False after it
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'create_task'
shit
self.bot.loop
yes
seems like working
other way could be outdated
now the bot's forcing me to type something between 1980 and 2022
isn't that what you wrote
yes
👁️ 👁️ so now it's working
this is a positive statement
I love the way it works so much
it's running through 3 classes after one-another
and passing through the results
so at the end they all go to one database
->
-> bot
Nah
^
mine
Yours is probably too advanced
If you wan a mystery, figure out how a solution to this: I need to upload an image in a message, then edit the message to show a new uploaded image
Without using links
I'm 99% sure that it's impossible
in an about me?
yeah
let me try something
thx
it says i ping u but if u look at my profile its just a bunch of numbers
@umbral night
Nope
why not?
how can I open a chrome tab, wait, then close it?
subprocess.call([CHROME, "https://youtube.com"])
await asyncio.sleep(50)
os.system('taskkill /im chrome.exe /f')
that is what I've tried, but chrome doesnt close
is there an easier way to make it so i can say !Help and !HeLP (with mixed caps incase of an accident or whatever) and it works?
without having to add a million aliases
yes, gimme a moment
thx
Now this will make your bot take a little more to respond, but just add
case_insensitive=True
to the line where you define bot/client, it should look something like this
bot = commands.Bot(command_prefix="!", case_insensitive=True)
ah, thanku for this, should've known
awesome
Keep in mind, the bot may lose performance due to this
all good
alright, as you please
ty
how would i make my text go down a line
to make it look easier to read and neater
Add a new line?
yeah
ig
how would i do that tho
async def perks(ctx):
embed = discord.Embed(title="*perks*", description="`1x boost = custom role+pic&link perms` `2x+ boosts = lowmod+bypassgw reqs`", colour=0x36393F)
embed.set_thumbnail(url=ctx.guild.icon_url)
await ctx.send(embed=embed)```
this is what i have
Just use \n
add a new line
how can i ban someone and keep their messages?
or use triple quotes ```py
"""
1x boost = custom role+pic&link perms `2x+ boosts = lowmod+bypassgw reqs
"""
!d discord.Member.ban
await ban(*, delete_message_days=1, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.ban "discord.Guild.ban").
ty
set delete_message_days to None
mkay
manually?
Yea
by pressing enter?
where
await send(content="Hunter\nuwu")```
async def perks(ctx):
embed = discord.Embed(title="*perks*", description="`1x boost = custom role+pic&link perms` `2x+ boosts = lowmod+bypassgw reqs`", colour=0x36393F)
embed.set_thumbnail(url=ctx.guild.icon_url)
await ctx.send(embed=embed)```
oh
yeah
Embeds cant use \n
they can, my bot uses it
how can I open a chrome tab, wait, then close it?
subprocess.call([CHROME, "https://youtube.com"])
await asyncio.sleep(50)
os.system('taskkill /im chrome.exe /f')
that is what I've tried, but chrome doesnt close
\:) vs :)
Oh well ig it works in this case, because the embed isnt registered as an embed till you send it
oh right,
yeah, I'm sure those work since I'm fully awake
But in discord itself, like here, backslash in embeds is just a backslash
Ig i confused the two lol
Lmao
Uh so I have await member.edit(nick = unidecode.unidecode(str(member.name))) which according to the nextcord docs, should work as it only passes in the nick param... although I get nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Timeout must be a "datetime.datetime" or "datetime.timedelta"not _MissingSentinel even though im never using timeout
You might need to update nextcord, it seems to fixed in the latest release
how do i fix this
discord.errors.HTTPException: 429 Too Many Requests (error code: 0): You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently.
so how do i fix it
yeah lol
you cant, you just have to wait
damn
i cant self host and there arent any good, free ways to host
gonna frequently get rate limited on replit
damn
sadly there are no good free hosts
are you following any sort of tutorial
just wondering
mk
also dont put your discord bot token on the actual code itself
your repl.it code is indeed public
store it in an environment variable
ik
i have
ive used replit in the past
then tried self hosting on vsc for a bit
but now that isn't an option
so back to replit + uptime robot
Oracle free tier
or AWS free tier
AWS doesn't have a free tier, they have a free trial
At least I don't think so? But I'm probably wrong
Oh, wait a free tier is a free trial
@umbral night u can get a free Oracle VPS for life if u got a credit card 👀
Idk then
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
!d discord.Guild.get_member_named
get_member_named(name, /)```
Returns the first member found that matches the name provided.
The name can have an optional discriminator argument, e.g. “Jake#0001” or “Jake” will both do the lookup. However the former will give a more precise result. Note that the discriminator must have all 4 digits for this to work.
If a nickname is passed, then it is looked up via the nickname. Note however, that a nickname + discriminator combo will not lookup the nickname but rather the username + discriminator combo due to nickname + discriminator not being unique.
If no member is found, `None` is returned.
would i use this instead of @client.command() @maiden fable
or am i stupid
it's an event
yeah
whats after that
if you're doing client.event you'd need to do client.process_commands(message) also then
what do you want to do?
i like it
just for fun or..? Because that will be triggered everytime a message is sent
?
no every time i say "vest" or someones name
not just anyone
only people i add to the code
admins mods etc
it'll ping them
you would require their names then
yeah
like name_list = ['vest', ....]
not the ()
oh
If you want all commands to not required a prefix you could also pass an empty string to command_prefix
not all commands
only this one
and then
@client.event
async def on_message(message):
if message.content in [a name list variable]:
member = await bot.getch_member(user ID)
await message.channel.send(member.mention)
you'd need a name list variable, and likely a dictionary with their name : id
uh
i mean you have to get the member objects of each of the people you want it to work on
yeah
so a list and dictionary can do that
@client.event
async def on_message(message):
if message.content in name_list = 'vest', 'example', 'example':
member = await bot.getch_member(user ID)
await message.channel.send(member.mention)
sorry im still new @spring flax
so is this what you meant
no i have to create-
um
how do i do this
Nope that's wrong
Hello trying to make a Anti Token join, basically it bans/kicks people who joined fast and started spamming is that's possible or not?
if message.content in ["vest", "example"]:
ah
!d discord.Member.joined_at
An aware datetime object that specifies the date and time in UTC that the member joined the guild. If the member left and rejoined the guild, this will be the latest date. In certain cases, this can be None.
@client.event
async def on_message(message):
if message.content in name_list = ["vest", "example", "example"]:
member = await bot.getch_member(user ID)
await message.channel.send(member.mention)```
And in the next line,
member = message.guild.get_member_named(message.content)
await message.channel.send(member.mention)
so will this work? @maiden fable
oh
@client.event
async def on_message(message):
if message.content in name_list = ["vest", "example", "example"]:
member = message.guild.get_member_named(message.content)
await message.channel.send(member.mention)
is that the proper indentation? i just guessed
@maiden fable and is that what u meant?
No...
what
Do you know what lists are?
Okay..then before starting i suggest getting a hang of the python basics
It'll help substantially
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
starting this specific command?
bc ive done quite alot so far
Before starting with discord.py
yes
Since it can be a bit complicated or difficult if you're not familiar with the python basics
This is a good start ^
sure, since you don't need to constantly host. Just learn in vsc
yep im on that page
ok
where does it get put out?
my code*
like once ive done something using basic python
oh
ctrl + ~ to open terminal in vsc
you know like how youve finished making a command, you move to discord and use the command
what do i do once ive finished something using normal python
yeah, so for basic python it will be controlled from your terminal
ah ok
It'd be in visual studio code itself
Yep
guild = client.get_guild(930167279281401906)
channel = guild.get_channel(944270496659279882)
msg = await channel.fetch_message(944461110717841448)
thats my code, but I get this error
Who is available to help me with an issue?
I can try
it is basically that the guild is None.
What's your current full code?
That's more of a #editors-ides question
you can fetch the guild in that case
!d discord.ext.commands.Bot.fetch_guild
await fetch_guild(guild_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild") from an ID.
Note
Using this, you will **not** receive [`Guild.channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.channels "discord.Guild.channels"), [`Guild.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.members "discord.Guild.members"), [`Member.activity`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.activity "discord.Member.activity") and [`Member.voice`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.voice "discord.Member.voice") per [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member").
Note
This method is an API call. For general usage, consider [`get_guild()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_guild "discord.ext.commands.Bot.get_guild") instead.
its a coroutine which makes an api call to return a discord.Guild object
the bot isn't ready when u r getting the guild
For dynamic cooldown if i have
def custom_cooldown(message):
if message.author.permissions.manage_messages:
return None #bypass mods
else:
return commands.Cooldown(1, 900) # one per 15m
####
@bot.command()
@commands.dynamic_cooldown(custom_cooldown, commands.BucketType.guild) #one per fifteen minutes per guild if author not a mod
async def s(ctx):
pass
Mhm?
Because i put bucket type guild, if a nornal user firsts uses the command and triggers the cooldown, then a mod can't too and has to wait
!d discord.ext.commands.dynamic_cooldown
@discord.ext.commands.dynamic_cooldown(cooldown, type=BucketType.default)```
A decorator that adds a dynamic cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
This differs from [`cooldown()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.cooldown "discord.ext.commands.cooldown") in that it takes a function that accepts a single parameter of type [`discord.Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") and must return a [`Cooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Cooldown "discord.ext.commands.Cooldown") or `None`. If `None` is returned then that cooldown is effectively bypassed.
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
New in version 2.0.
Lemme see...
Is there anything i can do to change this? Would reinvoke be the only option?
But how would that help?
I want it to be guild cooldown for normal members, but mods can always bypass
Wait
maybe check if the author has the role and remove the cooldown for them
"maybe"
So reinvoke?
I mean i tried finding to no extent.
Whats bad about reinvoke?
It is just a waste of resources imho. I mean, raising an error, handling it, revinoking and stuff yk
Unfortunately, this is the sucky part of the commands extension, you sometimes find yourself doing weird monkey patches and fighting for control over how the extension behaves. The only solution is to either continue that or process commands yourself.
.....?
Mind elaboratimg on process commands youself?
It's pretty simple. Parse the message content yourself. Implement your own command classes. Whatever it is you have to do.
Just to be clear, I'm not promoting this approach over feuding with the commands extension
Well, dpy allows to make yr own Commands class.. That is why there is a cls arg in the bot command deco
!d discord.ext.commands.command
@discord.ext.commands.command(name=..., cls=..., **attrs)```
A decorator that transforms a function into a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or if called with [`group()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.group "discord.ext.commands.group"), [`Group`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group").
By default the `help` attribute is received automatically from the docstring of the function and is cleaned up with the use of `inspect.cleandoc`. If the docstring is `bytes`, then it is decoded into [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") using utf-8 encoding.
All checks added using the [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") & co. decorators are added into the function. There is no way to supply your own checks through this decorator.
cls arg can be used to pass in a custom command class
Might as well just implement your own @command decorator at that point.
No need lol
Better than passing cls=... for every single command you declare.
Hmm true tho
@command decorator is also pretty minimal, it's literally 3 lines of code.
Indeed
What are those lines?
just pass the args and kwargs from the deco to the Command class
Something like this
def command(*, cls=..., **kwargs):
def decorator(func):
return cls(func, **kwargs):
return decorator
@bot.command()
async def fight(ctx, member: discord.Member):
global fighter
global fighter2
embed = discord.Embed(
description=f"""{ctx.author.mention} has challenged {member.mention} to a fight!
Do you want to accept or decline? (yes/no)
"""
)
await ctx.channel.send(embed=embed)
fighter = ctx.author
fighter2 = member
p1hp = 100
p2hp = 100
dmg = random.randint(10, 30)
def start_choice_p1(ch1):
return ch1.author == fighter2 and ch1 in ("yes", "no")
ans = await bot.wait_for("message", timeout=60.0, check=start_choice_p1)
if ans.lower() == "yes":
while p1hp > 0 and p2hp > 0:
embed = discord.Embed(description=f"{fighter.mention} it is your turn. What would you like to do?")
await ctx.channel.send(embed=embed)
async def choice_p1(p1choice2):
return ctx.author == fighter and p1choice2 in ("hit", "kick")
p1choice2 = await bot.wait_for("message", timeout=60.0, check=choice_p1)
if p1choice2.content == "hit":
embed = discord.Embed(
description=f"You have hit {fighter2.mention} for {dmg}hp! They now have {p2hp - dmg} left!"
)
await ctx.channel.send(embed=embed)
p2hp -= dmg
else:
embed = discord.Embed(
description=f"You have kicked {fighter2.mention} for {dmg}hp! They now have {p2hp - dmg} left!"
)
await ctx.channel.send(embed=embed)
p2hp -= dmg
embed = discord.Embed(description=f"{fighter2.mention} it is your turn. What would you like to do?")
await ctx.channel.send(embed=embed)
async def choice_p2(p2choice2):
return ctx.author == fighter2 and p2choice2 in ("hit", "kick")
p2choice2 = await bot.wait_for("message", timeout=60.0, check=choice_p2)
if p2choice2.content == "hit":
embed = discord.Embed(
description=f"You have hit {fighter.mention} for {dmg}hp! They now have {p1hp - dmg} left!"
)
await ctx.channel.send(embed=embed)
p2hp -= dmg
else:
embed = discord.Embed(
description=f"You have kicked {fighter.mention} for {dmg}hp! They now have {p1hp - dmg} left!"
)
await ctx.channel.send(embed=embed)
p2hp -= dmg
if p1hp == 0:
embed = discord.Embed(description=f"{fighter2.mention} HAS WON!")
await ctx.channel.send(embed=embed)
elif p2hp == 0:
embed = discord.Embed(description=f"{fighter.mention} HAS WON!")
await ctx.channel.send(embed=embed)
else:
embed = discord.Embed(description=f"{fighter2.mention} has cancelled the fight!")
await ctx.channel.send(embed=embed)
@fight.error
async def on_fight_error(ctx, error):
if isinstance(error, asyncio.TimeoutError):
embed = discord.Embed(description=f"Time's up, the match has been forfeited.")
await ctx.channel.send(embed=embed)
did i mess up the wait_for syntax?
cuz it doesnt work
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
oh mb
Why are your checks async functions?
In ur check use chl.content in …
The check shouldn’t be async
changed it but it still doesnt work
can you add url in discord embed field name
Not ans.lower() it should be ans.content.lower()
can somebody please help me with making this?
where i can put important peoples names in my code and the bot pings them once said in a text channel
important people meaning admins, owners, mods etc
so i can say the name without using a prefix
and i can say it in a sentence
Does anybody know a online Python IDE?
Which has Tkinter library
hello how send message if value is true?
How to make a scrims bot

