#discord-bots
1 messages · Page 1121 of 1
@slate swan :white_check_mark: Your eval job has completed with return code 0.
<generator object <genexpr> at 0x7ff29ef3fca0>
it does
https://discord.com/developers/docs/tutorials/hosting-on-heroku
TIL this also exists
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
@commands.command(aliases = ["панель", "Панель", "профиль", "Профиль", "prof", "Prof", "p", "P", "п", "П", "g", "G", " g"])
async def command_control_panel(self, ctx):
img = requests.get("URL", stream = True)
img = Image.open(io.BytesIO(img.content))
img = img.convert('RGBA')
img1 = requests.get("URL", stream = True)
img1 = Image.open(io.BytesIO(img1.content))
img1 = img1.convert('RGBA')
img1M = requests.get("URL", stream = True)
img1M = Image.open(io.BytesIO(img1M.content))
img1M = img1M.convert('L')
idrawImg = ImageDraw.Draw(img)
font = ImageFont.truetype('./Шрифты/picsel.ttf', size = 60)
font1 = ImageFont.truetype('./Шрифты/picsel.ttf', size = 50)
author = ctx.author.name
tag = ctx.author.discriminator
text = f'{author}#{tag}'
counter = 555 - len(text) * 23
counter1 = 555 - len(text1) * 21
idrawImg.text( (counter, 40), text= text, font=font, fill = (91,141,199,25))
idrawImg.text((counter1, 530), "123", font=font1, fill = (91,141,199,255))
url = ctx.author.display_avatar
url1 = requests.get(url, stream = True)
url1 = Image.open(io.BytesIO(url1.content))
url1 = url1.convert('RGBA') # конфертировал аву в РГБА
url1 = url1.resize((300, 300), Image.ANTIALIAS)
url1M = Image.new('L', url1.size, 0 )
idrawM = ImageDraw.Draw(url1M)
idrawM.ellipse((0, 0, 300, 300), fill=255)
img.paste(url1, (406, 170), url1M)
img.paste(img1, (0, 0), img1M)
img2 = img
idrawImg2 = ImageDraw.Draw(img2)
idrawImg2.arc((400, 168, 706, 469),start=0, end=0, width=10)
img2.save('./ImageS/profile.png')
file = discord.File("./ImageS/profile.png")
await ctx.send(file=file, view=class_control_panel(ctx.author.id))
Dear forgive me, tell me what is wrong. he gives it out, then he doesn't.
ping by.....?
I wanna drown in a glass of water again
...?
Amm
drown in me
property mention```
Returns a string that allows you to mention the given user.
Isn't that a bit too small for u?
if you put the water up your nose bruh you will probably die
💀 thats not drowning in the water, its the water getting in your body
same thing eh
lmao
how about directly injecting water into your lungs
does someone know an nsfw(real) api?
(real)
i already have an nsfw(anime) api
ph api
yes
what? that exist?
it probably does
i couldnt find any on google
what about xv
I'm probably gonna get muted if I run the pypi command for an async nsfw api wrapper
😭
no it's for good cause
LX no ban pls
I'm gonna get warned for sure
Not really server-appropriate @slate swan @swift pumice
oop thanks 😭
oh im sorry i didnt know
👍
that's a server banner
and only unlocks after 2 boosts iirc
it uses image manipulation and a task to see how many members are online and offline
and creates images and edits them
use the PIL module with a task to see the number of online members and create images
and set the server banner
I can't even imagine changing the server banner every x min
ah yes, ratelimit
Dear tell me what is the problem? this happens randomly with commands. i.e. error or not
LMAO
guys with discord.py if u send a command with an txt file attachment how can i make it so the bot reads it and writes it in another txt file
!d discord.Message.attachments
A list of attachments given to a message.
^ use that @severe bone
alr ty
Lemme try figuring that out
Can u share some code?
Hello bro. Is there any bot which will autokick in 24 hours if you don't get that role etc..?
This isn't the correct channel to ask this type of question. We can help u code that type of bot though
@commands.command(aliases = ["панель", "Панель", "профиль", "Профиль", "prof", "Prof", "p", "P", "п", "П", "g", "G", " g"])
async def command_control_panel(self, ctx):
lvl = cursor.execute(f"SELECT юзер_уровень_чат FROM users WHERE id = {ctx.author.id}").fetchone()[0]
img = requests.get("URL", stream = True)
img = Image.open(io.BytesIO(img.content))
img = img.convert('RGBA')
img1 = requests.get("URL", stream = True)
img1 = Image.open(io.BytesIO(img1.content))
img1 = img1.convert('RGBA')
img1M = requests.get("URL", stream = True)
img1M = Image.open(io.BytesIO(img1M.content))
img1M = img1M.convert('L')
idrawImg = ImageDraw.Draw(img)
font = ImageFont.truetype('./Шрифты/picsel.ttf', size = 60)
font1 = ImageFont.truetype('./Шрифты/picsel.ttf', size = 50)
author = ctx.author.name
tag = ctx.author.discriminator
text = f'{author}#{tag}'
text1= f'LVL {lvl}'
counter = 555 - len(text) * 23
counter1 = 555 - len(text1) * 21
idrawImg.text( (counter, 40), text= text, font=font, fill = (91,141,199,255))
idrawImg.text((counter1, 530), text= text1, font=font1, fill = (91,141,199,255))
url = ctx.author.display_avatar
url1 = requests.get(url, stream = True)
url1 = Image.open(io.BytesIO(url1.content))
url1 = url1.convert('RGBA') # конфертировал аву в РГБА
url1 = url1.resize((300, 300), Image.ANTIALIAS)
url1M = Image.new('L', url1.size, 0 )
idrawM = ImageDraw.Draw(url1M)
idrawM.ellipse((0, 0, 300, 300), fill=255)
img.paste(url1, (406, 170), url1M)
img.paste(img1, (0, 0), img1M)
idrawImg.arc((405, 168, 706, 470),start=0, end=359, width=5)
img.save('profile.png')
file = discord.File("profile.png")
await ctx.send(file=file, view=class_control_panel(ctx.author.id))
where URL there are direct links from google drive
can u print img.content?
Img
Img1
damn, I can't show the mask now because I'm not at home. I went to work (the problem there is that he is doing everything well. then it gives an error. either it's in the cloud, although it's Google drive. or you need to buy hosting.
Uh, can u send me the url to which u r sending a GET request?
aren't they the ones on top?
meh
meh
So the URL is https://drive.google.com/uc?export=download&confirm=no_antivirus&id=137EzkeyUKAIYSxnWSEP3ulsQpYfISnUJ?
@slate swan can u afford to save the image and then use the Pillow module?
should I upload images from the disk? it's slow so I didn't do it(
Well u should do that, if the image remains the same
Okay I'll try
Hunter's so smart
whats the best place to host a discord bot(free)?
😔
self host it...?
depends on how much time your device runs a day
not really helpful
other?
you can't really find good services to host your bot for free, you have to BUY a vps
or use AWS for 12 months free 😔
if you got a credit card you can get a vps free for 3 years
ew which one?
one year from aws, one from google cloud and another one from oracle
lmao
loool
File "main.py", line 71, in task
if member.activities and 'discordoofi' in member.activities[0].name:
TypeError: argument of type 'NoneType' is not iterable
member activity does not have a name
how do i fix that
discordoofi?
cant send actual invite
it just stops the task when it happens
yeah because of the error, you can use try except clause for it not stop
.name returns None.
Nah not for me
!e "a" in None
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | TypeError: argument of type 'NoneType' is not iterable
see the error
thats not even your code?
I use it in my bot, It returns user activity
I said i use it in my code
For the info command
And it outputs the user activity
The name of the activity.
maybe the library designer was high when he wrote Optional[str] here.
member.activities[0] returns None
oh wait I'm dumb
sorry
for member in guild.members:
role = discord.utils.find(lambda r: r.name == 'Supporter', member.guild.roles)
if member.activities and 'discofi' in member.activities[0].name:
print(f"{member} ✅")
if role in member.roles:
continue
else:
await member.add_roles(discord.Object(id=921720262217568268))
await fluf.send(f'gave supporter role to {member}')
elif member.activities and 'discoroofi' not in member.activities[0].name:
print(f"{member} ❌")
if role not in member.roles:
continue
else:
await member.remove_roles(discord.Object(id=921720262217568268))
await fluf.send(f'removed supporter role from {member}')
where do i put try except
if member.activities and 'discordoofi' in member.activities[0].name:
TypeError: argument of type 'NoneType' is not iterable
Ok?
i never used try and except
instant realisation of my mistake
you can just py if member.activity and member.activity.name: if member.activity.name: # do something
Returns only if the activity is Game. discord.Game.name isnt optional and is a slimmed down version of discord.Activity only
That's why "Playing"
note someone can be in spotify and fortnite and both are stored in activities
it would be None for a user with just an emoji in their status too
Better to just do an "if None" check before using it
I added the playing by my self
if "ActivityType.playing" in str(member.activities):
memberactivity = "**Playing** "+member.activities[0].name
Its a game after all
Yes
anyways don't overthink and just use an if check it makes ur life easier
after the for loop
or after both if statement'es
you just want to see that the member has a link in their custom status right?
yes
what's your python version?
idk im using replit
2nd line isnt required ig..?
i forgot to add something, it should be py if "some text" in member.activity.name :...
Oh got it
it should be inside the for member in ... loop
oh
💀 i was thinking of using a walrus operator but dont really think its needed here
see if that code works
works nice
no errors
does it do what its' meant to
yesss
Finally me done with my custom prefix thing
buttttttttttttttbut it keeps dming me "gave role to' same person again and again
show your updated code
looped until guild.members gets completed
add a "break" or "return"
@tasks.loop(seconds=40)
async def task():
await bot.wait_until_ready()
guild = bot.get_guild(921366728016011324)
fluf = bot.get_user(716707479005823036)
for member in guild.members:
if member.activity and member.activity.name:
role = discord.utils.find(lambda r: r.name == 'Supporter', member.guild.roles)
if member.activities and 'discoroofi' in member.activities[0].name:
print(f"{member} ✅")
if role in member.roles:
continue
else:
await member.add_roles(discord.Object(id=921720262217568268))
await fluf.send(f'gave supporter role to {member}')
elif member.activities and 'discorloofi' not in member.activities[0].name:
print(f"{member} ❌")
if role not in member.roles:
continue
else:
await member.remove_roles(discord.Object(id=921720262217568268))
await fluf.send(f'removed supporter role from {member}')
here
wait thats the one without the if member.activity and member.activity.name:
everything else is same
show the updated one because a single indent can change a lot of results
here
if member.activities and 'discoroofi' in member.activities[0].name: dont need this line anylonger
replace with if 'discoroofi' in member.activity.name
cause you're already checking the activities
okayy
Why does the bot send nothing when you mention a user?
@bot.command()
async def card(ctx, user: discord.Member = None):
if user == None:
user = ctx.author
image = Image.open("fons/user_card.png")
font = ImageFont.truetype("fons/font/GOTHIC.TTF", size = 80)
print(1)
name = user.name
tag = user.discriminator
date_format = "%d %B %Y"
print(2)
draw = ImageDraw.Draw(image)
draw.text((725,279), f"{name}#{tag}", font = font, fill="#ffffff")
draw.text((600,400), f"{user.created_at.strftime(date_format)} года", font = font, fill="#ffffff")
print(3)
avatar = user.avatar_url_as(size = 128)
avt = BytesIO(await avatar.read())
img = Image.open(avt)
img = img.resize((479, 478)) #
image.paste(img, (120, 359)) #
print(4)
image.save("user_card.png")
await ctx.send(file = discord.File("user_card.png"))
print(5)
is it possible to make something like siri with py-cord(discord.py fork that can detect sounds)?
well, if you do not mention the participant, then it will take the form of the one who entered the team, right?
huh?
you indented your code wrong
and that's why it doesn't work
async def my_hook():
bot.conn = await aiosqlite.connect("name.db")
bot.cur = await bot.conn.cursor()
Is it important to make this for a db?
yes, it is I just meant that how can bot.conn and bot.cur be accessed within the get_prefix function
and connecting to the db every time a message is sent....seems a bit off
Let me ask a pro guy
hm, it should be possible to do something like
async def my_hook():
bot.conn = await aiosqlite.connect("name.db")
bot.cur = await bot.conn.cursor()
bot.setup_hook = my_hook
def get_prefix(...):
...
bot.command_prefix = get_prefix
that is if I'm not being dumb
Oh yea
bot can get value in get _prefix if there in no value for guild it will make a new value with guild I'd and > as a default prefix
Ig?
...?
I really not able to understand what I have to write in my_hook thing
But that have no connection with sqlite
Like we use classes as template
...? template?
Like i can use this function when i need to connect to db?
not the function, the botvar
What botvar
what is indented?🤔
my_hook or my_hook()
!indent
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
Learn basic python btw
(Me not offending you)
ahem ahem
😂
!botvar
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
You mean me speaking about me
Means i can use it in get_prefix when i connect to db?
Funny sticker 😂
u can use it after the setup hook is called, so yes
@slate swan in get_prefix
What arguments i need to take?
||I|| ||don't|| ||know||
I also don't know
Dude...🤦♂️ 🤦♂️
Just guiding if not know indentation
making a discord bot is not a very good beginner project
ah, it takes two parameters, bot, message
Ahhahaahah
Message where the comamnd is executed?
yes
the message object of the context message
Like i type >help
It goes in the message
yes
And bot guild I'd?
bot means bot, if it was guild id, it would named guild_id xD
My brain out cause of sql
¯_(ツ)_/¯
guild_id = message.guild.id is what
you wanna know something, human != car
might as well wanna become the world's firstest human car
Like personification in English
(☉。☉)!→
ya ur brain really needs oil
Yes me mad that i started discord.py without learning python fully
well, that's technically not personification too....
but nvm am not gonna give english lessons here so uhh
damn thats a lie
I will never believe this!
not our fault, don't tell us that
Personification means realtting something to ourself
I realted car to my brain
nobody asked you to 
bro, u said ur brain needs oil. How does that make any sense
Anyway me start sqlite code bye!
If i would need help I'll ask
personification occurs only when an abstraction is represented as a person
Replace oil with petrol
then u related it with a car, when u personify, u use something that a human would do which is equivalent to oil and car in this case
ᕙ( ͡◉ ͜ ʖ ͡◉)ᕗ
okay we are way off topic now
and my brain has probably reduced to half due to the dpy server
I myself think that wouldve been way worse if someone asked me to
save the effort for another time if one does
believe what i said 🔫
🙁
I want to become doctor idk why me learning coding
i dont even know how to code 
brain does need oil the problem is how many types of it you would need to keep it as productive as it used to be
You have big brain
long term goods require some effort..
no, i have a big keyboard which i use to google 😎
Anyway let's get off of this topic and get to dpy
unfortunate to know
Same with me just replace big with small
I finally made my shows parser ds bot
Woo
You all have big brain but i have small(really)
thanks. ig
Learn them and use
fuck it, like I care
they were being sarcastic
I was being sarcastic too
what
ok
?
Bro why my welcomer bot got rate limit from discord?
use the actual user object not the class
that's what i don't know how i'm going to do
you need an instance of disnake.User not the class itself
not even an instance, an actual user object
yeah yeah ;/
more and more confused bro
I have already been given 3 different answers on 3 servers
I will do the command again
and
you have to accept in an argument which takes the actual user object, and uses that to access the ID
not the class for the User object
just have it passed into the func
def open_acccount(user):
...
users[str(user.id)] = {}
''' and call the command using '''
open_account(ctc.author.id) #if in a prefix command
and I see no point in making that function asynchronous
only if the data is static
or if changed manually
TypeError: BalCommand.open_account() takes 1 positional argument but 2 were given
Hey @slate swan!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
can I see the code?
nice spam
wtf?
your code is faulty, really faulty
!code format it like this
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
it's harder to view it otherwise
async def my_hook():
bot.conn = await aiosqlite.connect("name.db")
bot.cur = await bot.conn.cursor()
Ashley do i need to use the create table in the my_hook function?
sure, why not?
But i am getting one problem
where else did you plan to use it anyways
not this code
problem is?
I want help to standardize all these job titles. There are different titles here in a file. I want to do it using python. for eg , There is (vice president - engineering, vice president- technical) so it should be (vp eng, vp tech) and so on. So please if anyone can help me or provide easy method to do it. I will pay if anyone is willing to do it.
!rule 9
and that doesnt seem too long, you can manually edit that
and its not related to discord bot
that too
Automating it would def be faster
!rule 7
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
meh
still too much work
or am just too lazy
what
wasnt referring to you
why not
cuz meh
you're meh
ash feeling kinda rude today
last time i checked, i was ryuga
mood swings
literally even the function is declared as asynchronous, makes me wanna cry
there isn't anything asynchronous being done in there
the read-write operations are sync
swas: "ah yes put async here it will make it asynchronous"
the only thing async is get_bank_data which i think it also sync code inside async function
Yeah that yes but if disnake is async then I'll use async funcs
Yeah
also json as db 🤮
He uploaded a vid making that with postgre
GOOOD
async def get_data(): return __import__("json").loads(await (await __import__("aiofiles").open("uwu.json")).read())
is what I can think of
imports in one line, bad
now swas... your last task is to write tests
just an example, god
uwu.json lmfao
ash moment
imagine not ✨ return ✨ ing the data
mmaybe i should change my pydis nickname
😐 was just an example
😩it triggers me somehow, i write worse examples anyways
But uwu.json>>
just read it again
everything in one line, bad
get used to it 🤷♂️
still ignoring the fact that json
Why u name var same 😑
why not use a lambda? Also, u need a load not loads, there
why...?
and no lambda, I hate lambda
await f.read() will not parse the json data by itself, you'll have to use the loads function to parse it
u r not using read....?
Nvm u r also using await and they don't work in lambdas
my bad, fixed it
its commands.Cog
iohhh
and stop using globals.
lol i was only testing stupid misake
my webhook is not sending, am i doing something wrong?
from_url is an awaitable
I doubt that’s it
no, my other test command works which is in a diff cog
is on ready called once? because you load the cog after the bot is ready.
frick me lmfao my cog file was called Events.p and not .py
im not sure
With the way that the internals work, I.e the metaclass used to mark and register events & commands, will always trigger before even connecting to the API
hey andy 👋
Infact, I've seen a lot of people experience issues because the cog loads before the bot is ready
👋
Is that why they’re async now?
I have no clue as to what the reason was behind the change. I can assume that there was no BAD reason to switch to async as, discord.py is in an async context anyways. But most often than not, cog loading will still be before connecting to the gateway as I'll assume you connect in setup_hook and not on_ready
no, the cog is being loaded before the bot is running
is that correct?
class _Command(Command):
def __init__(
self: "_Command",
func: Callable[..., Any],
**kw: Any
) -> None:
setup(func, **kw)
super().__init__(func, **kw)
bot.command = partial(bot.command, cls=_Command)
bot.group = partial(bot.group, cls=_Command)
how to set cls for all bot.command without doing bot.command(cls=_Command) multi times? may someone help me please?
anyone know about sqlite?
#databases for sqlite and other database modules
ty
np
you could subclass
class Bot:
def command(name=discord.utils.MISSING, cls=_Command, **attrs): return super().command(name, cls, **attrs)
!d discord.ext.commands.Bot.command has a cls kwarg
@command(*args, **kwargs)```
A shortcut decorator that invokes [`command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command "discord.ext.commands.GroupMixin.add_command").
Or what TheMaster said
Self is missing
i already did that is it okay?
class Command(commands.Command):
def __init__(self: "Command", func: Callable[..., Any], **kw: Any) -> None:
setup(self, func, **kw)
super().__init__(func, **kw)
commands.command = partial(commands.command, cls=Command)
commands.GroupMixin.command = partialmethod(commands.GroupMixin.command, cls=Command)
class Group(commands.Group):
def __init__(self: "Group", *args: Any, **attrs: Any) -> None:
setup(self, *args, **kw)
super().__init__(*args, **attrs)
commands.group = partial(commands.group, cls=Group)
commands.GroupMixin.group = partialmethod(commands.GroupMixin.group, cls=Group)
That probably would work but I would recommend subclassing Bot like I showed and also Group
ty xd
anyone?
@client.command(aliases=["log", "logs", "audit", "audit-logs", "audit-log", "auditlogs"])
@commands.has_permissions(view_audit_log=True)
async def auditlog(ctx, lmt:int):
idk = []
str = ""
async for entry in ctx.guild.audit_logs(limit=lmt):
idk.append(f'''User: `{entry.user}`
Action: `{entry.action}`
Target: `{entry.target}`
Reason: `{entry.reason}`\n\n''')
for n in idk:
str += n
str = str.replace("AuditLogAction.", "")
embed = discord.Embed(title=f"{ctx.guild_name}", description=f">>> {str}", color=0x2f3136)
await ctx.reply(embed=embed)
guild.name
🤔
change ctx.guild_name to ctx.guild.name
Hunter is so smart
so we're not gonna talk about str = ?
Thanks for the sarcasm
Ah, yes.
str = "Some String I Don't Care About"
member_name = str(member.name)
Ok, I've seen enough
I hope you liked the first episode of Everyday Python Practices. See you tomorrow!
I'm definitely unsubscribing
Hunter's humour is even more broken than I expected
til I have humor
if payload.emoji == ":envelope_with_arrow:"
im running this with a reaction message, but when i click the reaction its returning false almost like im reaction to a different mesage, but im using the actual emoji not text
typecast the emoji to be a string
Might also wanna send the code
im doing this, is this what you mean?
sure
basically this is what ive got so far, everything but the emoji works fine
you should know what typecasting means
*TYPECAST
i dont
That seems like u r shouting on him
stressing on the fact
no ideas what typecasting is
they just mean str(payload.emoji)
hunter is so kind ❤️
oooh,
That is known as typecasting since str is a type and u r converting payload.emoji to string, so u r "casting" it to a string
pains me i didnt try that before, but cheers
ahh makes sense, never heard the term before
Same
average python pros who learned python using dpy
f
would scare the shit out for breakfast
gave me goosebumps lmao but the snake sure is cute
totally not me
how is a python cute👀
it is what it is
weird ppl
See, even Asher agrees but nvm
I hate you hunter
it is what it is
snakes are cute 😩 yellow albinos ❤️
I feel u 🫂
people have their own uniques tastes ig
you guys dont have a sense of humour, that's it
¯_(ツ)_/¯
if u said a lamia or snake girl i would still speak up for u atleast
im ded||snakes|| serious tho
di...snake
lmao what the
deadsnakes~

reference: they provide python installations for linux debian
thats innovative
f hd quality
everybody has a broken humour here
Ya'll might wanna take this to an ot channel
waiting for mods
how would i automatically have my bot create a new line once a certain amount of characters are typed out
im trying to remove the reaction after the if statement
async def on_raw_reaction_add(self, payload: nextcord.RawReactionActionEvent):
find = utils.SERVERS.find({"_id": str(payload.guild_id)})
user = self.bot.get_user(payload.user_id)
for data in find:
ticket = data['Ticket ID']
channel = data['Channels']['Ticket']
if str(payload.emoji) == "📩" and user != self.bot.user and int(payload.message_id) == int(ticket):
How am i best doing it, my previous methods i've had nothing but error, my head taken a beating on this one
for example, i do not like how this looks and would prefer the mentions to go onto a new line one they take up a certain amount of space
do \n after participants
thats not automatically
thats hard coding it for the mentions to go onto a new line
which would have the name issues
you wanted mentions to go onto a new line?
automatically based on how much space the characters take up
desc = f"{data} \nMap: {mapLink}\nParticipants: {participants}"```
!d textwrap
Source code: Lib/textwrap.py
The textwrap module provides some convenience functions, as well as TextWrapper, the class that does all the work. If you’re just wrapping or filling one or two text strings, the convenience functions should be good enough; otherwise, you should use an instance of TextWrapper for efficiency.
thats my code, but i want to modify it so that once a line becomes too long, it creates a new line
thank you
how can i solve it, if message deleted and the message is a picture the bot on_message_update send the picture?
!d discord.Message.attachments
A list of attachments given to a message.
ty
message = await self.bot.get_channel(int(channel)).fetch_message(int(ticket))
await message.remove_reaction("📩", user)
returning:
if member.id == self._state.self_id:
AttributeError: 'NoneType' object has no attribute 'id'
is there also a way to automate pagination based on much data is being read?
for example, im using pandas to log some biking data and want to recall it in discord in groups of 10.
the way i have my code now, i have to manually create new pages and pull information manually in groups of 10, which although does what i want, is inconvenient
i never use self, so idk if thats the issue or theres another issue that im not realizing :/
can u show the the code around if member.id == self._state.self_id:
this is from the discord library
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
Traceback (most recent call last):
File "D:\Documents\Programming\Python\Hyplex Bot\venv\lib\site-packages\nextcord\client.py", line 445, in _run_event
await coro(*args, **kwargs)
File "D:\Documents\Programming\Python\Hyplex Bot\discord\cogs\ticket.py", line 53, in on_raw_reaction_add
await message.remove_reaction("📩", user) # remove the reaction
File "D:\Documents\Programming\Python\Hyplex Bot\venv\lib\site-packages\nextcord\message.py", line 1592, in remove_reaction
if member.id == self._state.self_id:
AttributeError: 'NoneType' object has no attribute 'id'
that just means that member has no "id" parameter thing
no it means member is None
the user variable is None
ya which is why it doesnt have "id" as a parameter
ive changed to pull from payload.user_id but then i get a
File "D:\Documents\Programming\Python\Hyplex Bot\venv\lib\site-packages\nextcord\client.py", line 445, in _run_event
await coro(*args, **kwargs)
File "D:\Documents\Programming\Python\Hyplex Bot\discord\cogs\ticket.py", line 51, in on_raw_reaction_add
await payload.message_id.remove_reaction("📩", payload.user_id) # remove the reaction
AttributeError: 'int' object has no attribute 'remove_reaction'
change it to discord.Object(id=payload.user_id)
same issue:
Traceback (most recent call last):
File "D:\Documents\Programming\Python\Hyplex Bot\venv\lib\site-packages\nextcord\client.py", line 445, in _run_event
await coro(*args, **kwargs)
File "D:\Documents\Programming\Python\Hyplex Bot\discord\cogs\ticket.py", line 51, in on_raw_reaction_add
await payload.message_id.remove_reaction("📩", nextcord.Object(id=payload.user_id))
AttributeError: 'int' object has no attribute 'remove_reaction'
your message variable was correct earlier... revert it
an integer value doesnt have remove reaction as an option
sound, that fixed it
i got this AttributeError: 'int' object has no attribute 'remove_reaction' both times...
so your issue is solved now ig?
i was thinking about this time, so maybe we were thinking about different tracebacks
@bot.command()
@commands.has_permissions(kick_members=True)
async def timeout(ctx, user: discord.Member = None, time: str = None):
time = humanfriendly.parse_timespan(time)
if user == None:
await ctx.reply(f"Please add a user to timeout!")
if time == None:
await ctx.reply("Please add a duration for the timeout!")
await user.timeout(until = discord.utils.utcnow() + datetime.timedelta(minutes = time))
embed=discord.Embed(description="", color=discord.Colour.red())
embed.set_author(name=f"Successfully timed out {user} for {time}", icon_url="https://cdn.discordapp.com/emojis/934179741425090590.webp?size=96&quality=lossless")
await ctx.reply(embed=embed)```
Error:
```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'```
its datetime.timedelta
you probably imported datetime from datetime
yeah we all good
great
so import timedelta from datetime?
from datetime import timedelta, datetime
datetime.now() # ✅
timedelta(seconds = 5) # ✅
alright thanks
OR:
import datetime
datetime.datetime.now() # ✅
datetime.timedelta(seconds = 5) # ✅
you pick which you like
sorry sarth
😩 its oki, you got it this time
async def bikeDatalogBook(ctx, df, buttons, current):
page1 = discord.Embed(title = "logged Dates:",
description="\n".join(df["Date:"].iloc[0 : 10]), color=discord.Color.blurple())
page1.set_footer(text=f"Page 1")
page2 = discord.Embed(title = "logged Dates:",
description="\n".join(df["Date:"].iloc[11 : 20]),color=discord.Color.blurple())
page2.set_footer(text=f"Page 2")
page3 = discord.Embed(title = "logged Dates:",
description="\n".join(df["Date:"].iloc[21 : 30]),color=discord.Color.blurple())
page3.set_footer(text=f"Page 3")``` is there a way to automatically make new pages every 10 data inputs?
or do you have to manually add new pages in the code the way im doing it now
how do i delete the bots message
my own bots message
after certain timr
?
!d discord.ext.commands.Context.send @slate swan
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for non-interaction contexts.
For interaction based contexts this does one of the following...
see the delete_after kwarg
Ooohhhhh
you ca basically ```py
await ctx.send("message", delete_after = seconds)
same for any send methods
okay (:
stumbled onto my next error, had this working before with the same code
message = await self.bot.get_channel(int(channel)).fetch_message(int(ticket))
await message.remove_reaction("📩", nextcord.Object(id=payload.user_id))
channel_name = f"ticket-{str(user)}"
guild = message.channel.guild
author = user
transcript = user
support = get(guild.roles, name="Staff")
overwrites = {
guild.default_role: nextcord.PermissionOverwrite(read_messages=False),
guild.me: nextcord.PermissionOverwrite(read_messages=True),
author: nextcord.PermissionOverwrite(read_messages=True),
support: nextcord.PermissionOverwrite(read_messages=True)
}
new_channel = await guild.create_text_channel(channel_name, overwrites=overwrites)
returns this:
Traceback (most recent call last):
File "D:\Documents\Programming\Python\Hyplex Bot\venv\lib\site-packages\nextcord\client.py", line 445, in _run_event
await coro(*args, **kwargs)
File "D:\Documents\Programming\Python\Hyplex Bot\discord\cogs\ticket.py", line 68, in on_raw_reaction_add
new_channel = await guild.create_text_channel(channel_name, overwrites=overwrites)
File "D:\Documents\Programming\Python\Hyplex Bot\venv\lib\site-packages\nextcord\guild.py", line 1192, in create_text_channel
data = await self._create_channel(
File "D:\Documents\Programming\Python\Hyplex Bot\venv\lib\site-packages\nextcord\guild.py", line 1070, in _create_channel
payload = {"allow": allow.value, "deny": deny.value, "id": target.id}
AttributeError: 'NoneType' object has no attribute 'id'
What do I need to know before I can start making discord bots?
how do i get the bot loop in lightbulb to run_in_executor
@commands.Cog.listener()
async def on_reaction_add(reaction, user):
channel = discord.utils.get_channel(762287224796348446)
if reaction.message.channel.id != channel.id:
return
if reaction.emoji == ":Brawlhalla:":
role = discord.utils.get(user.server.roles, name="Brawlhalla")
await user.add_roles(role)``` How do I enter the emoji into rection.emoji ?
your ideal language, like here python
basics of asynchronous programming, OOP and you should be pretty comfortable with basic things like loops and conditions, etc
Yeah but more specifically
Cool, anyone got a good resource to learn about asynchronous programming?
Oh and also being good at reading documentation
??
Is that a library?
no
check pinned messages in #async-and-concurrency
It's not?
nope
Generally speaking, it's a library
Though people have different definitions for "library" vs "module" vs "framework"
I thought that was the same thing? Whats the differences?
!d asyncio.get_event_loop
asyncio.get_event_loop()```
Get the current event loop.
If there is no current event loop set in the current OS thread, the OS thread is main, and [`set_event_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.set_event_loop "asyncio.set_event_loop") has not yet been called, asyncio will create a new event loop and set it as the current one.
Because this function has rather complex behavior (especially when custom event loop policies are in use), using the [`get_running_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop "asyncio.get_running_loop") function is preferred to [`get_event_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_event_loop "asyncio.get_event_loop") in coroutines and callbacks.
Consider also using the [`asyncio.run()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.run "asyncio.run") function instead of using lower level functions to manually create and close an event loop.
Deprecated since version 3.10: Deprecation warning is emitted if there is no running event loop. In future Python releases, this function will be an alias of [`get_running_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop "asyncio.get_running_loop").
ah right, i can just do that
how's it a library
Can someone help?
library is basically a collection of modules, but that term is loosely used
I'm not the right person to ask on specifics regarding terminology. Often though, people will call most everything a "library", except in certain cases where they'll call it a "framework" (e.g flask)
users[str(user.id)] this dict has no key called "bank"
guys, the on_message_edit log the links, why?
and every message
@client.event
async def on_message_edit(before,after):
channel=client.get_channel(980392593781309480)
now = datetime.datetime.now()
current_time=now.strftime("%H:%M:%S")
current_date=now.strftime("%d/%m/%Y")
embed=discord.Embed(color=0x66ff66,description=f"Üzenet megváltoztatva itt: {after.channel.mention}",timestamp=datetime.datetime.utcnow())
embed.set_author(name=f"{before.author}", icon_url=before.author.avatar_url)
embed.add_field(name=f"Előtte",value=f"{before.content}", inline=True)
embed.add_field(name=f"Utána",value=f"{after.content}", inline=True)
embed.set_footer(text=f"Üzenet ID: {after.id}\nDátum: {current_date} • Idő: {current_time}")
await channel.send(embed=embed)
So hello, I need some help. I am trying to make a bot, and I'm trying to use the bot subclass thingy, and trying to use on_message to send a message every time a message that has some...thing(?). (as an example, if an user sends a message saying only "rule 1" the bot sends a message saying "Rule 1, follow Discord TOS")
(code is here)
1 #bot.py
2 import os
3 import discord
4 import random
5 import time
6
7 from dotenv import load_dotenv
8 from discord.ext import commands
9
10
11 load_dotenv()
12 TOKEN = os.getenv('DISCORD_TOKEN')
13 GUILD = os.getenv('DISCORD_GUILD')
14 bot = commands.Bot(command_prefix='€')
15 client = discord.Client()
16
17 #@client.event
18 #async def on_ready():
19 # print(f'{client.user.name} has connected to Discord :)')
20
21
22 @bot.event
23 async def on_ready():
24 print(f'{bot.user.name} has connected to Discord!')
25
26 #@bot.event
27 #async def on_message(message):
28 # if message.author == client.user:
29 # await bot.process_commands(message)
30 # return
31
32
33 @bot.command(name='ping', help='| Ping Pong, tells you the bot\'s latency :)')
34 async def ping(ctx):
35 #wait ctx.channel.send = 'pong'
36 await ctx.reply(f'pong! {round(bot.latency * 1000)}ms')
37
38 random_message = 'Random message :D'
...
(the messages I want to print, and a bunch of if statements that make it print stuff, I know this is inefficient and should be optimized)
....
71 if message.content == 'random message':
72 response = random.choice(random_message)
73 await message.channel.send(response)
74 await bot.process_commands(message)
...
bot.run(TOKEN)```
if the
26 @bot.event
27 async def on_message(message):
28 if message.author == client.user:
29 await bot.process_commands(message)
30 return```
block is uncommented, the commands stop working
Obviously, commands are only processed if your bot is the one to send said command
One way to accomplish this is to have a dict of keywords to messages, and the bot will send that message based on that dict
hm
like this?
Random_message = [
'random',
'messages',
'in',
'discord :)'
]
First_ message = 'This is the first message :D'
because that's what I'm doing
the whole bot worked before I made it use the bot subclass
I could just convert it back to using discord.Client
why do i get this error when i run my slash command, but it returns no error in the log and it does as i was coded?
idk, we can't see the code?
- You are NOT subclassing Bot
- You are using
BotandClientfor the same app, which is invalid - You are creating one event with
Clientand others withBotbut running onlyBot
and idk how to fix it lol
also, my bad, idk what to call the bot thingy
You aren't sending an actual response back for the interaction, you are just send an embed to the channel
Bot object while bot is the instance of that Bot object
I figured I need to replace the client thingies but idk what to replace them with lol

am i better off changing interaction to ctx to avoid this?
.....? slash commanda take an Interaction not a Context
alrighty
how can i pass the error?
just send back a message to the interaction...
how do I replace the client event with a Bot event?
response message *
omg thanks sparky, what a wonder you made
so, how do I do this?
with interaction.channel.send(...) i still get this error
interaction.response.send_message
interaction.channel access the TextChannel object and sends a normal message
i want to send to a specific channel regardless which channel the command was used
Thanks
¯\_(ツ)_/¯
how do I replace the Client event with a Bot event?
interaction.response.send_message smh
hi, i have a "small" problem. my on_message_edit work, but
@client.event
async def on_message_edit(before,after):
channel=client.get_channel(vizsgalati)
now = datetime.datetime.now()
current_time=now.strftime("%H:%M:%S")
current_date=now.strftime("%d/%m/%Y")
embed=discord.Embed(color=0x66ff66,description=f"Üzenet megváltoztatva itt: {after.channel.mention}",timestamp=datetime.datetime.utcnow())
embed.set_author(name=f"{before.author}", icon_url=before.author.avatar_url)
embed.add_field(name=f"Előtte",value=f"{before.content}", inline=True)
embed.add_field(name=f"Utána",value=f"{after.content}", inline=True)
embed.set_footer(text=f"Üzenet ID: {after.id}\nDátum: {current_date} • Idő: {current_time}")
await channel.send(embed=embed)
@bot.event ...?
Let me bring microscope 🔬 real quick
they all are @bot.events
and the ones that aren't, are commented
is client.user an issue?
before.content and after.content is empty
yo @sick birch, is there an issue with using client.user in a bot that uses Bot
and if there is, how can I replace it?
so how do I replace it?
what does that mean
you named your Bot client?
...no?
this ^^
I'm trying to?
I also just realized that the reason the block of code was there, was to stop recursion so
Idk what the issue is, I'm more used to people who come here knowing python
commands.Bot inherits from discord.Client, which means that everything that client has, bot also has it
if you used Client before, then you should have no problem changing everything to a Bot instance and it's going to work
71 if message.content == 'random message':
72 response = random.choice(random_message)
73 await message.channel.send(response)
74 await bot.process_commands(message)
does that have an issue?
yeah, processing commands doesn't do anything there
welp
maybe it was an embed, or an attachment that was edited
or something like this:
I mean, I'm trying to use on_message to send these
point is, there are a million different reasons for why it could be empty before and after
what I just realised is that random_message is a single string
what do you wanna take out of a string
it's tied to a string
!e
import random
random_message = "I'm a simple string"
response = random.choice(random_message)
print(response)
@heady sluice :white_check_mark: Your eval job has completed with return code 0.
s
random_message = 'random_message'
idk how to help u :/
!e
import random
random_message = [
'this',
'is',
'a random',
'group of strings'
]
response = random.choice(random_message)
print(response)
@unique bronze :white_check_mark: Your eval job has completed with return code 0.
is
you basically don't want to use YT tutorials
since that's mostly crappy implementations and outdated lib use
!d discord.ext.commands.Command
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.
apparently the name random_message isn't "defined", although it is
please use #discord-bots for self-serving commands
where ?
in my bot
Are you asking for help ?
yes
Can you send the code pls
yeah, you want to use a database instead of json
import random
random_message = [
'this',
'is',
'a random',
'group of strings'
]
@bot.event
async def on_message(message):
response = random.choice(random_message)
await message.channel.send(response)
that's basically what it does
if u want the full thing, I can send it
and it says that random_message is not defined ?
yes
File "/home/iravii/python-stuff/CommandBot/Commanbot.py", line 78, in on_message
response = (first_message)
NameError: name 'first_message' is not defined
that's the error
first_message is not random_message
Ehh send the whole command
the whole code?
71 @bot.event
72 async def on_message(message):
73 if message.content == 'random message':
74 response = random.choice(random_message)
75 await message.channel.send(response)```
this is what's relevant ig
ok and where is first_message ?
wait your codes are not the same, can you please just send the command with lines wich are problematic pls
wdym
ah that's bc I send 2 different command things
they're basically the same
in any case you don't use your first_message in your event, so why not remove it?
I do use it
where so ?
...
I'm sorry but in those two event that you sent you don't use first_message
75 if message.content == 'random message':
76 response = random.choice(random_message)
77 await message.channel.send(response)
78
79 if message.content == 'first message':
80 response = (first_message)
81 await message.channel.send(response)
82
83 if message.content == 'second message':
84 response = (second_message)
85 await message.channel.send(response)
86
87 if message.content == 'third message':
88 response = (third_message)
89 await message.channel.send(response)
90
91 if message.content == 'fourth message':
92 response = (fourth_message)
93 await message.channel.send(response)
94
95 if message.content == 'fifth message':
96 response = (fifth_message)
97 await message.channel.send(response)
98
99 if message.content == 'sixth message':
100 response = (sixth_message)
101 await message.channel.send(response)
102
103 if message.content == 'seventh message':
104 response = (seventh_message)
105 await message.channel.send(response)
106
107 if message.content == 'eighth message':
108 response = (eighth_message)
109 await message.channel.send(response)
110
111 if message.content == 'ninth message':
112 response = (ninth_message)
113 await message.channel.send(response)
114
115 if message.content == 'tenth message':
116 response = (tenth_message)
117 await message.channel.send(response)
118```
here
that's horrible code, I know it is
ok i see
so don't say anything about that
dw
haha
what?
commands be like
this made me laugh
ah
so first_message is above your bot_event ? @unique bronze
bot_event is above that
random_message isn't defined?
...it is defined above that massive wall of if statements
yeah weird
indeed
@bot.event
async def on_message(message):
first_message = '...'
if message.content == 'random...':
response = random.choice(random_message)
await message.channel.send(response)
...```Is your code like this @unique bronze ?
what if you define it inside of the function
no, it's like
...
random_message = 'random message :)))'
@bot.event
async def on_message(message):
if message.content == 'random_message':
response = random.choice(random_message)
await message.channel.send(response)
...
it worked when I used Client instead of Bot btw
that's why it doesn't work... You have to define a variable inside your function if it's outside the event it'll be not defined
bruh
alright
thank you
np
is there a specific decorator for the "has_any_role" for slash commands? or do they work on both commands and slash?
very common question you can ctrl+f that in this channel
IT WORKS
What is a token?
What you use to log into your bot, sort of like a password
Idk how to log into my bot, less so how to create it. Im guessing I have to do some stuff on Discords website? Is there a tutorial for that?
That's right, and it's simple enough
you should learn more about Python i think
Hey can somoene help me please
Nakime's been upgrading the youtube video code of an economy bot for like half a year, but not much improvement
In regards to the bot permissions, what should I tick? Is it possible to edit this later?
Yes, it is
For testing, just go for admin
sure, ask your question
its a pic
Then what? ive created it but how do I give it functionality?
Send it
Check the docs for a simple bot code
@jovial urchin You have to create an url for invite your bot, but this is in the doc
Which doc?
wait a sec
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Here you got everything you need for create your bot.
If I understand correctly: I need a url to where my code is and then add it to the Interactions Endpoint URL?
That's optional, don't need it
the code is not in the url
is only the url for the bot access to your account and then join the server
I don't understand. How do I give the bot the code?
in your text editor
at the end of your code you'll add py bot.run('Your token that you get from the website')
You don't give it code, you log in as your bot, and you send API requests to control your bot
To log in: py bot.run("token")
Examples of sending API requests to control your bot:
await ctx.send("Hello, world!")
which sends a message in discord
ah I see. And to keep the bot alive I need to stay logged in and have the script continue to run?
yeah or pay for hosting
Generally token is an encrypted string that contains some data about person who is authorising with it, and only server side knows how to decrypt it
You just need to stay connected to the events gateway yeah
iirc, the first two halves of a discord token will be the user's snowflake, then it'll be the epoch for when the user was registered
The last half will be the actual auth stuff, the HMAC
Probably wrong I haven't looked at that in a long time
I could see the first part being somewhat useful
So if I just leave my script running on my computer it would be all good?
If your computer keeps running and your script process doesn't get killed then it's ok
Notice that you have to refresh it sometimes otherwise the bot will disconnect by itself
@jovial urchin
wdym by refresh it? Kill the script and run it again?
Yeah
for exemple you'll use your command prompt, and for run your file you'll have to do File\path\main.py, this will execute your code but at some point you'll have to run it again from a new window
Whats the reason for this?
I can't tell you exactly why, but I think it's because of inactivity.
Inactivity from who?
users who don't use the bot
Can't I just have my bot make some random API calls every now and then to make it seem alive?
Everything is possible 🤷🏻♂️
Wondering if anyone has another approach to doing timed events with Discord bots. I've been poking around and many places suggest the tasks extension, but what if the bot is rebooted for whatever reason? All the queued tasks would be gone, right? I plan to make some features that allow users to go on "quests" that might take a few hours to complete. When complete, the bot will send a message on discord that the event has concluded. Any thoughts?
What sort of quests
And yes if the bot is not always connected, the qeued would be gone
@low badger
has anybody made a discord bot that allows you to see what number a player was to join a server (so like you could do /joinnum player, and it'll show if they were the 23rd person to join the server for example)?
Best way I can think to describe it is Farmville like. If you plant a crop it takes 30 minutes, 2 hours, 6 hours, etc. The user doesn't have to keep the window open, the server handles it all. But I need a system that works even if the server is disrupted, so I figure I'd store each event in a database with a time of when it should be completed. The only thing I'm missing is how the server will check the database for when events are complete. Hope that makes sense. Do people even play Farmville anymore? haha
I guess most mobile games work off mechanics like this as well.
I thought it would be cool lol. Right now they can do dailies that give them exp and gold. But questing would give you more gold to send gifts to friends, stuff like that.
So far the users have enjoyed it.
I could have the bot check on regular intervals. Maybe ever 60 seconds or so, but that would not be accurate. I also thought of having the bot check at startup and set it's check again time to whatever the lowest remaining time was within the task list itself.
But that has issues too. If the oldest one is 1 hour, but someone submits a new one that takes 10 minutes, then it's off again. So maybe it sets it's time to the lowest remaining timer every time someone starts a timed event.
The way you want to do this is actually quite different; instead of doing background events what you want is to make it appear as if they happen in the background, but actually just calculate them on the fly. If a user gains X coins every hour, for example, then you only need to update the actual number of coins the use has when they next interact with the bot, using a last_updated field or similar to calculate the interval
Oh interesting. And this will stay consistent even if the bot has to be rebooted?
Schrodinger's coins, so to speak 
Haha
It should be yeah, since it doesn't need any tasks running to update it, as it runs 'lazily' when needed
I'll look into this, thank you!
How can I use the discord.ext.tasks extension to create a task that's run at a certain time on a certain interval? For example, at 0000 UTC, every 2 days? From the docs it seems the time attribute and the hours, seconds, minutes attribute are mutually exclusive
I don't think you can do that just with the kwargs, but you could do something like if (time.time() // 86400) % 2: return at the start of the task
Ah okay, that's unfortunate. I'll see if we can change up how the feature works, and if not I'll go with your idea. Thanks!
np
!d discord.utils.sleep_until maybe this will help as well?
await discord.utils.sleep_until(when, result=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sleep until a specified time.
If the time supplied is in the past this function will yield instantly.
New in version 1.3.
Yes
no new message, but messige notification. Help?
will do next time cutie
import discord
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
client.run('your token here')
In this script, why is on_message passed an argument and where does it get it from?
It gets called whenever there is a message and the parameter is the message that activated the function
message is the message object, it contains information like who sent the message, when it was sent, etc. message.content is the actual content of the message
But how does it know that a message was sent? And how does on_ready know that it is logged in
Discord's servers tell you through the websocket connection (referred to as the "gateway") when a message was sent
on_ready actually happens after discord.py's internal cache and everything else is ready to go
So discords servers tells me when anything at all happens?
Exactly
Whats the decorator for?
It's to let discord.py know that the following function is an event, and you should call it when it happens
Without the decorator it's just a plain old function that does nothing
You seem interested in how things work under the hood, I suggest you try to connect to discord's gateway without using a library like discord.py to get a much deeper understanding of how things work under the hood. I found it that way when I made a bot without using discord.py or any other wrapper
yooo making a discord bot, i can send hard coded embed messages but how can i send a user input embed message?
its for a stock/option bot im making
like to send alerts to a server
User input how? An argument in a command?
right in a way
lemme write an example
yall know how you can make your own discord bots, well i made a very simple bot. need to figure out how i can send custom embed messages. now for context, i know i can hard code the message using
embed = discord.embed (title="title", description="some crazy ass description", color=0x00ff4)
but what if i want to say like
!embed today we are going to talk about video games
and it sends that as an embedded message. for context the bots prefix is "!"
Well however you get it, if you can get it into a variable (which it should already be in one), you can just use that in the embed however you want
i have an idea but idk if its valid -> title = userinput(input = " ")
same for description
Id love that. How do I go about it?
and then just doembed = discord.embed (title=input, description=input, color=0x00ff4)
@bot.command()
async def embed(context: commands.Context, *, arg: str):
embed = discord.Embed(
title="You said:",
description=arg,
color=0x00ff4
)
await context.send(embed=embed)
Invocation:
!embed this is a nice sentence
If you need any help with that, ask in #965291516031549500 and feel free to ping me
My pleasure
whats deleted channel?
The thread #965291516031549500?
Not sure why it's showing up as #deleted-channel for you
If you want to access it click on the threads button at the top right, and go to discord-api-and-gateway
ah okay is it a thread to this channel?
Yes, it is
dont have access to it lol
It's more focused than this channel, more advanced you could say
Awsome ty
no worries
is it possible to change the discord.ui.Select width and height? may someone help me please?
hmm doesnt seem to work, but ima figure it out, just needed a start
No, not possible unfortunately
Doesn't seem to work how?
thx
And can I see the code/any errors you have?
Give me like 15 eating dinner
wait i fixed it lmao
im dumb
@sick birch what am i doing wrong, theres no errors, and when i type the command theres no response
code doesnt break tierh
either*
Mmm, did you do client.run(...)?
You are making an event, not a command
Ah good catch, didn't see that
yes at the bottom
ah okay , so gotta change it to @client. commad ?
How can I group commands together in cogs?
bet lets try that
Do you mean group commands/subcommands?
Also use the function that is currently in the string. It has the correct parameters for a command
AttributeError: 'Client' object has no attribute 'command'```
Grouping commands in cogs, using prefix
Also commands all take commands.Context instance as the first parameter
Like this:
@bot.group()
async def setup(ctx):
if ctx.invoked_subcommand is None:
return await ctx.send("Doesn't exist :rolling_eyes:.")
But like in cogs
Not sure what you mean by that, group commands?
Ahh okay, group commands
oh so it cant take "discord.message"
it should be the same, but instead of @bot.group() it's @commands.group()
Oh
No, first argument should always be the context, and other arguments like strings and integers after
Then to call it in the group command it would be
Just regular, nothing special about calling it
okay gotcha
You don't call the group, discord.py calls it for you when you call the command in discord
I am using nextcord
Yes, my point still stands
U need to use the commands extension https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html
Hmm, I must be confused then, cause I do @setup.command() when I am not in cogs
Do I not do that in cogs
i have that
Should still be the same
Hmm ok
okay ive tried like every possible way, even adding "context.message.send" but still doesnt work
Are you using commands.Bot instead of discord.Client?
So like this?
You've passed in the proper intents, enabled in the dashboard as well?
Seems right.. does it work?
at the very top i have "client = discord.client()" and then "bot = commands.bot()"
Use commands
or ig comment it out
that one
okay
You need to have either discord.Client or commands.Bot, but not both
You can always do an on_message then can still do commands
so instead of "client.event" id just have to replace "bot.event"
@sick birch Yup it worked
The grouping worked
Thank you, I am trying to get a verified bot
okay okay we're getting somewhere
Good luck! Hope it does
Bot development is not easy
No indeed, not without the right tools and a well structured bot
ahhh you guys are goats
Using a database can really get you somewhere tho
I saw you were using aiosqlite, maybe you'd like to look into an ORM to make it even easier/better?
Yea
I am using it for now
Making a dashboard in python is just hell nah
TS tho is Yes, I made a dashboard in TS actually
Works nice
Did you use a framework? If so, which?
nestJS for the backend
okay kings another question, if i want to add a gif into the embedded message, how would i go about doing that?
then the dashboard was react
Like as a thumbnail or the big image at the bottom?
React + TS, a time and tried combo. Good for you! 🎉
Yes, the backend server tho is hella confusing
Pulling ban analytics
timeout and kick anlytics
both perhaps
Ok so
You could do
embed.set_image(url="") or embed.set_thumbnail(url="")
gotcha
@commands.Cog.listener()
async def on_user_update(self, before, after):
#name
if before.name != after.name:
embed=nextcord.Embed(title="Name Change",description=f"{after.mention}",color=0xfd9fa1, timestamp=datetime.utcnow())
fields=[("Before",before.name,False),("After", after.name,False)]
for name, value, inline in fields:
embed.add_field(name=name,value=value,inline=inline)
await self.bot.get_channel(933978399280599080).send(embed=embed)
```can someone help me please?
datetime.datetime.utcnow()
oh
datetime is part of a module also called datetime
tysm!
import discord
client = discord.Client()
for i in client.guilds:
print(i)
@client.event
async def on_message(message):
if message.author == client.user:
pass
elif message.content[0] == "!":
await message.channel.send('Hello!')
with open("token.txt", "r") as f:
token = f.read()
client.run(token)
Why doesn't this print the guilds the bot is in? It is in 1 server currently
for i in client.guilds:
print(i)
is called before the bot is even ready
Ah, I need to wait for the on_ready call?
Why is the commands going twice
It just says the same thing twice
I am not running it anywhere else
you should wait for the bot to connect so use
!d discord.ext.commands.Bot.wait_until_ready

