#discord-bots
1 messages Β· Page 1068 of 1
@sick birch managed to get this with the inline thing, but why is there such huge space
Are you using the whitespace hack?
yes
That's probably why
They weren't meant to use the whitespace hack, gonna have to deal with it
if i do it any other way its totally broken
It's meant to look better when it's used like intended
Why not have the user's name and discrim as the field name, and their messages as the value?
because that would make it even longer
or equally as long
You don't even need fields, you can fit them all into the description which gives you more flexibility
oh i am fully aware
i was going to do that, then someone said you can do nice grids with it
is there an intended way to get 2 columns?
make only 2 fields both of which are inline
these are 3
Don't believe so. I know I said it's a bit grid-like, but that's only really works when you have a lot of name/value pairs which are approximately the same length
otherwise it gets a bit funky
Probably better to just use ljust with spaces to put it all in the desc
whats ljust
you mean subtract length of the current string from the longest string and add that as spaces to the current string
!e
print("user1#1234".ljust(20, ' ') + ' - ' + '500')
print("user2#5678".ljust(20, ' ') + ' - ' + '250')
@sick birch :white_check_mark: Your eval job has completed with return code 0.
001 | user1#1234 - 500
002 | user2#5678 - 250
something like that
lol i added that exact thing to a differnt thing the bot does
but i coded it myself
!e
print("user1#12dddddddd34".ljust(20, ' ') + ' - ' + '500')
print("user2#5678".ljust(20, ' ') + ' - ' + '250')
@scarlet sorrel :white_check_mark: Your eval job has completed with return code 0.
001 | user1#12dddddddd34 - 500
002 | user2#5678 - 250
where do i put this in my code
Above your bot constructor
But you had all intents, so I don't believe that's a problem
Can you print something as the first thing in the on_message?
any of this relevant or not even related
Yeah you're good, you have all intents
Can you print ctx.bot.game_states[str(game_channel.id)].game_over before the while loop?
So
print(ctx.bot.game_states[str(game_channel.id)].game_over)
while not ctx.bot.game_states[str(game_channel.id)].game_over:
...
printed False
any suggestions or ideas to try lmk @sick birch , as i got to go and wont be back for at least a few hours
is it wait_for("msg" ...) or wait_for("message" ...)?
async def on_message(message):?
thats the file
i got to go, any thoughts pm me @heavy shard, ill get back to em later
The second
Itβs just the normal event name without on_
def draw(self): # thanks copilot
match self.tries:
case 0:
return """
How to do this in python 3.8
it returns invalid syntax even when i import Match from typing
if and elif
U need Python 3.10 to use match case
you can't use Match case in 3.8, if elif is ur deal
yea thats what he said
!d typing.Match
class typing.Pattern``````py
class typing.Match```
These type aliases correspond to the return types from [`re.compile()`](https://docs.python.org/3/library/re.html#re.compile "re.compile") and [`re.match()`](https://docs.python.org/3/library/re.html#re.match "re.match"). These types (and the corresponding functions) are generic in `AnyStr` and can be made specific by writing `Pattern[str]`, `Pattern[bytes]`, `Match[str]`, or `Match[bytes]`.
Deprecated since version 3.8, will be removed in version 3.12: The `typing.re` namespace is deprecated and will be removed. These types should be directly imported from `typing` instead.
Deprecated since version 3.9: Classes `Pattern` and `Match` from [`re`](https://docs.python.org/3/library/re.html#module-re "re: Regular expression operations.") now support `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](https://docs.python.org/3/library/stdtypes.html#types-genericalias).
thats another thing, meant for regex.
oh
how can i put a @commands.cooldown(1, 10, commands.BucketType.user) in an if statement
how can i put a cooldown
in general
what do u mean
@cooldown(rate, per, bucket)
@command(**kwargs)
async def command_callback(ctx):
...
like this?
yes
use this @keen mural
bcz the bot is shit and hasnt been updated in 2 yrs
i mean like if they are missing an argument for example they still get a cd and i dont want that
it just broke 3 times this week
@slate swan
@bot.command(cooldown_after_parsing=True)
this will only activate the cooldown if the codes runs smoothly
@commands.cooldown(rate, per, type=<BucketType.default: 0>)```
put that above ur command function
it doesnt give errors if thats what you mean
yes
for example if amount=None i dont want it to have a cd
@client.command(aliases=['dep'])
async def deposit(ctx,amount=None):
if amount==None:
await ctx.reply("You must specify an amount to withdraw")
return```
or should i use an error handler instead
raise ValueError('Missing argument')
put that in ur code
@client.command(cooldown_after_parsing=True)
@commands.cooldown(rate, per, type=<BucketType.default: 0>)
@client.command(aliases=['dep'])
async def deposit(ctx,amount=None):
if amount==None:
await ctx.reply("You must specify an amount to withdraw")
raise ValueError('Missing argument')
#return```
set it blank if u dont want a message
I'd probably just have a global error handler to handle all the missing argument issues
Best not to repeat yourself in your code
but it would be a command specific message i need to send
Pretty sure with a global error handler, you can still say which argument you missed, like the name of it. Anything more specific than that, it has to be on a per command basis
In which case I'd make a command-specific error handler for seperation of concerns
or a long elif tree which checks the command names
unpythonic
how do i install dpy2.0 on replit?
hello
hi
Okay dude my bad
can you learn any type of coding here?
how do i install dpy2.0 on replit?
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
U need to manually install it via shell and set the version in the poetry file
how exactly
@sick birch so how do you think i can make this more ordered?
the code:
for i in range(0, math.ceil(secud * 2)):
if math.floor((i+1)/2) == math.ceil((i+1)/2):
list2.append(f"#{(i+1)/2}: {temp}, {nlist[i]}")
else:
temp = nlist[i]
debug = "\n".join(list2)
embedVar = discord.Embed(title="Leaderboard of users ranked by messages", description=f"{debug}", color=0xbafc03)
embedVar.add_field(value=f"{debug}", inline=False)
debug = await message.reply(embedVar)
await debug.add_reaction("ποΈ")
Definetely by making all the message #s on the same "column"
right
but the question is how
Find the largest name. add 5 for #XXXX, set that as the first argument for ljust
you have to learn python to make discord bots? certainly not
the name and discriminator are the same string in this
since its pulling all of the info from a huge file
ill do that tho
yes i figure it out now. i just have to restart.. cause i think some of my code are not gonna work :/
Don't tell me you're logging every message in a file?
Damn π³
there's only like 50k messages in there
text is very tiny in terms of space
computers are good at dealing with it
just a plain old text file?
yep
ah, that's very inefficient
so every time there's a new message, you append that to the text file?
not even
π¬
just open the entire text file as a string, add the new stuff to the end, then write the entire thing back
oh my
didnt know how to do fancy stuff when i wrote that part of the bot
should probably fix it
I'd probably just have an in-memory cache and periodically dump it to an actual database
And only have one record for each user, and increment the number for each message
nahhhhh
not enough data
this way i can have all kinds of fun commands
which i already have made
this leaderboard one included
then you might be interested in something like our metricity bot
oh nvm
Logging every message to a file should be fine π€ You don't have to override all data, just append
it is using append
why
I don't know about fine, it's still just a plain text file and vulnerable to data corruptions
that was very cheesy
Not if you just append i think
it lets us do a lot of very fancy stuff with metrics data, and has user messages in there
You don't rewrite full file, so
i do like metrics
It's not just that, it's a plain text file not meant for handling large amounts of data
Storing them into a db is obviously a better way to do that
and large mutations of it!
We used it frequently to figure out which channels get the most messages, etc
where is the actual bot in the repo
Basically a mini version of discord's search bar at the top right hand corner, which bots can't access
the actual bot goes by some other name here, don't remember what exactly
Ah it was @lusty spear
only 400 lines
.js π€’
come on, it's only 100mb
yeah that crashed my browser
I'm assuming you're only joking
I'm just saying that storing data into plaintext files is ok
if it's static, never changed, then sure maybe
Logging was and is done using files
if it's dynamic data i would steer clear of it
append only should be fine too
using text files isn't all that much of an improvement from JSON
its an improvement?
It is an improvement
since you can append, it's a little bit of one
wow
still vulnerable to the other flaws
im ahead of the game then
Json files in 99% of cases should be fully overwritten
And you can corrupt your file this way unless you do some kind of atomic write
u just need to know about with open
i do know!
then its easy
@scarlet sorrel I think you can learn sql and store your messages there (in case you need to access them later)
best choice
If you just want a log - text file should be fine
wym access them later
literally
i can just read the file
access them in efficient manner
thanks
you don't need to store message content, only other metadata like things such as user ID, channel ID, guild ID, etc
msg delete logs are against tos?
i would personally just save the object so its repr would be saved so i can access all of the message's info
well 90% of the time im trying to read every message anyway so cant be that much better
why even store messages when you can simply store the number...
Why did you use gino and not just sqlalchemy?
dude literally dyno does that
not really only large amounts of storing data but it is against tos if you have no reason
its not against tos
oh, nvm actually
ikr my 1 friend was telling me not to add
Why would you read every message?
youre welcomeπ
my bot probably breaks every rule of the discord TOS in some way anyway
nice bot
okay
i know it breaks this servers rules or whatever
helpful for other data
as in?
it would never get verified
what does getting verified do
Messages can get deleted, modified, etc
say you wanted to find out which channel gets the most traffic, having a 2 column table with user ID and the # of their messages won't help
it can benefit in allot of things actually
eh?
The biggest + would be that people actually trust your bot
Since it's been vetted by discord officially, and not some random bot that's going to get shut down in 2 weeks
and bigger ratelimits!
my server has 400 members and i dont even have community enabled on it, i hate the way discord forces you to do things in specific ways so i just try to stay under the radar
how does a bot get verified
its their app after all
well talking about channel traffic, you could simply store the channel id with the message amount, no? or you meant it to be user specific?
it needs to follow tos and it needs to be in 100+ guilds
its already in 11 guilds
ok
I was only providing an example. Storing other data like channel ID, guild ID, things like that opens you up to a lot more metrics data collection to help you figure out the right way to go with your server
hm inarguable
yea thats what i do
not ID tho
just name
because i was big stupid when i wrote that part and i literally cannot change it now because it would mess everything up
SELECT channel_id FROM messages WHERE channel_id = 12345 ORDER BY channel_id DESC
My SQL is rusty since I mostly use ORMs but you get the general idea
i do things manual
yeah one of the reasons to practice good code modularization early on
π§βπΎ
select * π
rip db
Now it's just useless π
@sick birch sqlalchemy is actually very close to sql:
select(Model)
.where(Model.column = "some value")
.order_by(Model.created_at.desc())
And you can do complex aggregations too
not much experience with sqlalchemy. I usually work with Prisma (the typescript client, not the python one)
but yeah, similar concept
It's hard to use something like prisma after sqlalchemy tbh π
pretty much the only library i use in my bot to help me do much of anything is tabulate
everything else is just as needed
actually i can just send the imports lol
wait they might get me banned from here
these are NOT my imports they are just something i found in a different yet similar bot to mine so its a good example
import os
import re
import glob
import math
import json
import base64
import openai
import random
import asyncio
import discord
import requests
import warnings
import wolframalpha
import urllib.request
from io import StringIO
import datetime as etad
from datetime import datetime
from tabulate import tabulate
from psaw import PushshiftAPI
import time as timeorsomething
from googlesearch import search
from icrawler.builtin import GoogleImageCrawler
could really do with some seperation of concerns
but m o u n t a i n
import datetime as etad
to fix the datetime error
just import datetime π€·
import datetime
now = datetime.datetime.now()
huh? why not
dude you cant
You can
^
@scarlet sorrel
so? just use datetime.datetime.now()
you cant
datetime is a class
^
!e py import datetime print(datetime.datetime.now())
@slate swan :white_check_mark: Your eval job has completed with return code 0.
2022-05-28 05:57:02.027491
dude thats not the same thing
datetime overlaps with datetime
datetime(module).datetime(class)
you are only importing datetime
!e
import datetime
now = datetime.datetime.now()
print(now)
print(datetime, datetime.datetime)
@honest laurel :white_check_mark: Your eval job has completed with return code 0.
001 | 2022-05-28 05:57:22.422595
002 | <module 'datetime' from '/usr/local/lib/python3.10/datetime.py'> <class 'datetime.datetime'>

Just access it from datetime: datetime.datetime
you are only importing datetime not datetime and datetime
trust me it causes errors
You don't have to import them
you do
π
forget it jesus
if you import the base module,you still have access to the objects and function inside it
you guys never had to work with time very much
I work as python dev for 2 years already, you sure?
yes
ok
i remember doing this.
am not saying it doesnt work, but as per the pep8 standards, thats incorrect.
How do you guys deploy discord bots?
VPS
I mean the process itself
i currently use railway.app which has github integration so i just need to create a project with the bot repository as base and enter the required envs
and a shell command as hunter mentioned forsure
please share bot.py
guys Please guide me about hosting
#python-discussion would be better place for this, cause #discord-bots
Please
Am New to bots hm π
@slate swan Have you attended AWS Summit
It's great
for AI
Follow the docs quickstart https://discordpy.readthedocs.io/en/latest/
Hm
Ya
Umm iI don't know anything about that
One minute
I am sending you details
Okay
This is a free user by AWS
Amazon Web Services
Umm
Suspicious
No
yeah not here please delete that or i will ping mods :))
Delete this
Ok
thank you <33
Hello Im Here To Help With Assignments And Etc! Dm For Help
Can you please recommend an IDE for python?
against the rule!
Thanks but I don't think it's allowed here
No I Mean Teaching!
i need help on python homework π
this is hard
Create a variable with the value 4
it's so hard broooo
not helping
vsc is good pycharm as well but its kinda heavy
sorry its denied!
Vscode
LOLL
I have it already
it was a joke, of course it's just x = 4
Or VS2022
ahh your wording is a bit confusing
im sorry
im trying my best to get helpers badge so i can teach people!
compared to pycharm which is 1200gb of ram
My laptop has 16GB of RAM
I've set up deployment using docker swarm and gitlab-ci, works like a charm for small-medium sized projects
nice
well the role is quite hard to get and just helping wont really get it
Well then how do i get it
you have to be actively helping
you need to help and master the language and you have to be active and humble ofc
Also helping in dms won't help you to get it..?
no
Roger That Ms.okimii!
π i still need to learn docker
ive been helping here on a daily basis for about a year and i still dont have the helper role so dont think it will be easy ;)
oki is a good helper
sarthak has been here for way more tho
no u
You can check where command was executed
It's not that hard to learn, you just have to start somewhere
actually, never really needed it, but imma learn it now
me who doesnt know how to even use a env: 
configs.py moment
haven't learned them nor used themπ
You can package any app into an image and run it anywhere, it's pretty useful
You won't have to setup your environment, dependencies, etc
@slate swan You just describe your build process like this:
FROM python:3.10-slim as build
ENV POETRY_VERSION=1.1.13
RUN apt-get -y update && apt-get -y install git
RUN pip install poetry==$POETRY_VERSION
COPY ./pyproject.toml ./poetry.lock ./
RUN poetry install --no-dev
WORKDIR /app
COPY ./src ./src
COPY ./config ./config
COPY ./resources ./resources
COPY ./alembic ./alembic
COPY alembic.ini main.py ./
ENV PYTHONPATH=$PYTHONPATH:/app/src
ENTRYPOINT ["poetry", "run", "python", "main.py"]
since you would set an argument thats a textchannel object just use the id attr
typehint the channel arg to the suitable channel types, you can use arg.id then
Can't you right click and copy id?
this seems easier than setting up an env everytime
Also code itself should look like this i think:
@commands.command(name="id")
async def get_channel_id(self, ctx: Context, channel: TextChannel):
await ctx.send(channel.id)
turn on developer options, you can hold on the channel and use Copy ID
Not sure about TextChannel here, maybe you can use some of the abstract classes
i.e. Snowflake
yes?
You can copy channel ids on mobile
It's the same app
a tablet and a phone have the same client lol
Did you enable developer mode?
channel_id needs to be an int
and dont use direct fetch calls
respond isnt a method....
oof
channel = bot.get_channel(id) or await bot.fetch_channel(id)
doesnt matter, a channel object still wont have it.
πΏ
!d discord.utils.get
um yea sure
discord.utils.get(iterable, /, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Changed in version 2.0: The `iterable` parameter is now positional-only.
Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable "(in Python v3.10)")s...
channel = discord.utils.get(ctx.guild.text_channels, name="channel_name")
print(channel.id)```
uh?
πΆββοΈ they had issue copying it
yea sure
!d discord.ext.tasks.loop
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
you can use any of these kwargs
issues keep getting worse....
this channels keeps getting more actib
honestly, the issues dont even relate to dbots-
agreed
you need to start the task using auto_send.start() as well
ahh lovely it works
Screw nitro, all my homies got empty wallets
wait before the bot is ready using the wait_until_ready method at the top of the task and start the task
Facts though
Alot of #databases questions get asked here
at least they got money
π
i told-
where?
already on
it's off by 1 space*
async def example():
await a()
await b()
All lines in function serverinfo have indent of 4 spaces, last line (await ctx.send(embed = serverinfoEmbed)) is indented with 3 spaces
ohh
nope still not working
Replit?
It usually causes poor intendation, use a real ide, fix the indents and paste it back
anyone?
indentation issue
done
Replit sucks at indents also why are you even using it? Personal preference or seen it in the tutorials
And yeah following naming convention: lowerCamelCase is not for python at all (UpperCamelCase is used in classes), use snake_case for variables
@slate swan I asked you to answer this question
Mention and cap emoji doesn't answer it anyhow
tutorial indeed
I just wanna know why are there so many replitters
And why not use the normal IDE
Like yall have PCs (don't mind me programming on phone 2 years ago)
REASONS WHY PPL USE REPLIT :
1. device issue
Some ppl dont have pc/laptop so they use replit
2. No knowledge
some ppl dont know that there are better ide than replit
It's hard to go back to anything else if you used a good IDE for a while

I personally use PyCharm because i use a lot of built-in features, VSCode is quite good too
vs code extensions
It's not the same π
im saying that vs code extension feature
- mobile IDEs exist
- that's why we tell them to not use replit
mobile ide π
Coding on mobile is pain and should be forbidden by international law
I used vscode before I got free jetbrains license π©
imagine using mobile ide
Pycharm professional feels very uh professional
huh
Exactly!
The only thing I don't like about pycharm lint is this
self.stuff: Stuff = None # lint says it's not supposed to be None so I gotta add it to typehint like Stuff | None```
Well, it's correct to add | None
mypy deprecated implicit Optional | None
But it's none π
facts
π₯²
Even better than wordpad
Any typechecker would complain about it
lmao
Just cat and tee into file
bruh
π Ok
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'member_count@honest laurel
ctx don't have member_count
it's a property of discord.Guild
!d discord.Guild.member_count
property member_count```
Returns the member count if available.
Warning
Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be specified.
Changed in version 2.0: Now returns an `Optional[int]`.
serverinfoEmbed.add_field(name= 'Member Count', value=ctx.member_count, inline=False)
``` correct?
Just read the message^
ctx.guild.member_count
thx
len(ctx.guild.members)π
still, ctx doesnt have the members property, its the Guild object which does
woah discord is offering nitro for free again
member_count faster than len(members)
Anyone here who is extremely experienced with working with discord api, kindly drop me a message
Im looking to engage someone
extremely experienced
Extremely uwu
lmao
yeah ik
me
aside from the fact I'm not getting engaged today, I don't think I'm experienced enough
lmfao
am I the only one who misread that question or.....
we all did i think
thats a call for andy
what is that anyway? because that could be anything from "has actually read and used the API doc instead of blindly copy-pasting from stackoverflow" to "has actually written parts of the Discord API"
contact discord developer support, ease
well, first of all if you have intentions of just making a bot, there are already libraries which wrap up the Discord API...
and i believe that most of the regulars here are no copy pasters
good to hear
hey guys will this rob command work:
async def update_bank(user,change = 0,mode = "wallet"):
users = await get_bank_data()
users[str(user.id)][mode] += change
with open("./data.json","w") as f:
json.dump(users, f)
bal = [users[str(user.id)]["wallet"],users[str(user.id)]["bank"]]
return bal
@client.command()
@commands.cooldown(1,60,commands.BucketType.user)
async def rob(ctx, member: discord.Member,amount,mode="wallet"):
await open_acccount(ctx.author)
await open_acccount(member)
sucesslist = ["Sucess","Caught","Failed"]
sucess = random.choice(sucesslist)
robbedmemberbal = await update_bank(member)
if mode == "wallet":
if amount > robbedmemberbal[0]:
mbed = discord.Embed(
title="leave the poor monkey alone",
description=f"he only has {robbedmemberbal[0]} monkeybux in his wallet!"
)
await ctx.channel.send(embed=mbed)
else:
if sucess == "Sucess":
await update_bank(member,-1*amount,mode)
await update_bank(ctx.author,amount,mode)
mbed = discord.Embed(
title="OOO NICE BANANA",
description=f"You robbed {member.mention} for {amount} monkeybux!"
)
await ctx.channel.send(embed=mbed)
elif sucess == "Caught":
await update_bank(ctx.author,-1*amount,mode)
mbed = discord.Embed(
title="HAHA SUCK IT MONKEY",
description=f"You were caught and {amount} monkeybux was confisticated from your wallet! (dnc if your balance becomes negative, monkey cops say u deserve it)"
)
await ctx.channel.send(embed=mbed)
elif sucess == "Failed":
mbed = discord.Embed(
title="L BOZO MONKEY",
description="the moment of opportunity to rob was wasted and the robbery failed"
)
await ctx.channel.send(embed=mbed)
```
try it and see,.... json is really unpredictable
while me with sqlite:
π
why would you do this lmao
idk how to do it with replit
use sqlalchemy instead
I'm bored
meanwhile me documenting things noones ever gonna see
||we|| ||are|| ||simply|| ||pointless||
+1 
honest question: is the consistent use of non-standard spellings a stylistic choice?
also consider what happens if the bot succeeds in subtracting the victim's balance but fails to update the thief's. now you've made monkeybux vanish into the void.
according to pep8 standards naming should make sense
not generally, i meant with reference to the code excerpt above: sucess for success, acccount for account, etc. makes my eyeballs itch. :)
but maybe as a crotchety old programmer who is out of touch with a younger coding culture, i'm missing something here.
(i.e. could be a stylistic choice intended to inflict discomfort on pedants?)
also the indentation of the else ...
(i mean, it will work, but is poor style)
otherwise, i can't see without more context why the command wouldn't work.
database transactions are atomic π
(If used correctly)
yeah. but makes the problem more complicated. if just saving to a file, perhaps update the data structure in a single function instead of using two function calls, one to subtract, one to add.
would be an improvement
Hah, yeah, files are unreliable
(from examining that code excerpt the author probably isn't ready for databases yet)
I can't read sometimes
same :)
i see a lot of pure discord.py. i assume that's more typical than, say, Red here (which I use, and am tracking the development branch + PR's + patches to stay up to date)? i appreciate the modularity of Red, but my bot is fairly niche, and wonder if pure d.py wouldn't have been a better choice.
the only thing is, i do appreciate Red's modularity and think I'd miss it if I changed things now.
If anyone 18+yrs is interested, I just started a project connecting discord and web 3
Need some discord.py devs if anyone knows some good ones
I'm using ubuntu20.04, but i dont think it really matters
pip install git+https://github.com/Rapptz/discord.py.git
thx
you should read the consequences of the update before upgrading - https://discordpy.readthedocs.io/en/latest/migrating.html
already know them
good
not only that...
should I list everything?
stupid pycharm... for what did i upgrade
Can you tell me how to calculate the list coin = ['COIN', 'ASCOIN'] and if the user enters the command .coin COIN it checks if there is an intersection point after .coin in the list and outputs either a runtime error actions
what would be involved in the calculation?
this is coin = ['PENTA', 'SPARK', 'PLYUM', 'TEPLOTA']
and the value variable specified by the user
if value == coin:
doing this gives me an error
let's take one of the coins... which one?
SPARK
ok, what do you know about a SPARK?
in what sense?
how about, in the same sense as you want to do this calculation
what are the instructions telling you?
Let's make it easier.
How do I check if a user-entered value variable is in the list coin = ['PENTA', 'SPARK', 'PLYUM', 'TEPLOTA']
if value in coin:
...
?
I'll try it now
let's go back to the spark coin... what are all the things you know about it?
Many thanks for the help
welcome
even I don't understand your point here tbh....
let's start with this calculation... what would the calculation do?
....?
I don't understand what he is talking about either.
lmao
are there instructions?
....
do the instructions say: "calculate the number of coins"?
jimm already helped me, you don't have to break your brain
if there are no instructions, I don't understand the purpose of the exercise?
if there -are- instructions, what are they?
π
Do you know how to work with the PIL library?
me? sorry, I've not worked with it before
not much but decent, though their docs are pretty much detailed -> https://pillow.readthedocs.io
how to make text not go out of bounds?
how do you measure the bounds?
Guys can someone tell me what could I add as a premium feature for premium bot , Idk what would be good to add
you could use the textwrap module for that
wait what
weird
import textwrap
margin = offset = 40
for line in textwrap.wrap(text, width=40):
draw.text((margin, offset), line, font=font, fill="#aa0000")
offset += font.getsize(line)[1]
an example
this is for me right?
yes it is, if that doesnt work, there are several more solutions
https://stackoverflow.com/questions/8257147/wrap-text-in-pil stackoverflow π is always there to copy the codes
text_body = f"""{DESCRIPTION}"""
this is my text
you might want to think about this problem, how would you know a letter of a particular size would fit into an area?
tbh, there's not point of premium features...
import textwrap
margin = offset = 40
for line in textwrap.wrap(text_body, width=40):
draw.text((margin, offset), line, font=font, fill="#aa0000")
offset += font.getsize(line)[1]
is this how it should be done?
hm set the margin and offset as necessary
Ik this is weird but whatβs the best way of making money if uknow what I mean
and the width
okay
find or invent somethign that someone else would want to buy
I dont think there will any be point of charging people money for a discord bot cz a lot of bots could do those stuffs for free, you could simply set up a donation system with a bit extra utilities, thin upon those then
Hmm true
What variable do I need to output here?
Can someone spend some time telling me a lot : bunch of features a bot can have because idk
I only know stuff like ticket system suggest warn ban and that stuff
Nothing to complex
why don't u just get the img size and use that to measure what u write
what are the -units- of the size of the image?
aren't images in pixels?
Pixels?
sure, that is one possible unit. and,
pil only works with pixels as far as i know
if you see an image, how else can you mesure it? what other units are there?
lmao lemme tell u u go take a 15cm scale and start measuring....
ohhh, another unit is cm!
name = int(user) this is what you are doing
u can use ctx.author.mention
so, you can find out how wide an image is, -in CM-, ahd how high that image is, also -in CM-

no, its embed field name
so, then you will know the size of the image in cm
yeah they don't work in titles and footers
Some mini games, moderation commands, music, useless commands, system like bank, casino, etc... umm and... idk?
only in description and values
not in field name too right?
and their are like a gazillion bots like that
yeah
u should try to focus and narrow down to a topic
@slate swanbecause you want to know if a string of characters will fit in the image
i meant for βοΈ
Cause discord's api is limited to create only these stuff....
Just don't make the bot >>>
no?
nah its about how u get creative
there are a lots of thing a bot can have
mine has some minecraft related commands and heavy image processing stuff
also other stuff from different web apis
Still it feels a lot limited... I mean ofc discord isn't a development or gaming site but a chat service anyways
is there a way to take a string, and -render- it, in a particular font, to see if that string would fit on the image, given the font is a particular size?
there might be a few limitations in the api but it's more than enough to support ur imaginations
whats point....
wait gotta check my old code
what module are you using to -render- text
pil Image.new and Imagedraw should work
ye
@slate swanthe point is, how will you know if a string of characters will fit on an image
draw = ImageDraw.Draw(bgimage)
draw.textsize(string, font) # returns a tuple with w, h```
then check if its larger than the main bg image
If you wanna learn stuff, good to start with these...
u can basically take the font size which is in pixels
and then check len of string
multiply...
why not just use built in functions
π nothing's unique now ig, so cant complain
lmao
are all the characters in the font the same width?
time to make a meme bot for the 387547th time
Make a dashboard music player to control your bot's music from site/app
and once it's out it won't be unique
indeed
there will always be people to follow suit
that would be more inconvenient for the user though
depends on the font
π«
so what u need is to be unique and a smash at the same time so that others don't stand a chance
use this instead
draw = ImageDraw.Draw(bgimage)
draw.textsize(string, font) # returns a tuple with w, h```
then check if its larger than the main bg image
@tight micayes. AND it depends on the -size- of the font too
Make your own spotify (without those annoying ads), no bots involved
use the spotify api ease
lmao u can just mod the Spotify app
or just use the brave browser
lol
the ads are on the client side
smort
yes
they are?
yeah
i see
downloads are on server side so no way arnd that
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
;/
@tight micamaybe, there is a way of taking a string, a font and a font size, and be able to tell how large -in CM- that string is, so then you know if it will fit on an image of a particular size
yes
command i think
centimetres
@slate swanextra emphasis
uhuh
just make a command which takes the string, font, and font size as the input
create a font = ImageText.truetypeorwhatever("fontname.ttf", fontsize)
then just do the thing i mentioned
wonderful idea
Will change with devices ig...?
what's the default size or a full scale size of an embed image again
it could
that's why you need the size of the rendered string
only ur screen size changes π
nope it's constant
I'll just go play ehh this is too much
Like in a 4k screen, more pixel density than one on an 1080 one, with the same dimentions?
zoom levels π
^
good... I think you get this idea
this is an example of how you need to be able to think
yeah correct just checked
Pixels come in many different sizes, each having their advantages and disadvantages. Larger pixels are able to collect more photons, due to their increase in surface area. This allows more photons to be converted into photoelectrons, increasing the sensitivity of the sensor. However, this is at the cost of resolution.
ok back to topic
That's camera resolution not display resolution
before someone rule7 us
lmao
I guess text strings and their size when rendered, is off the topic of discord bots?
but in any case.... -all- programming, is solving problems...
and you have to be able to think about problems
you might know how big a pixel is, in CM
not possible if CM = centimetre
lmao u take a joke too hard
I have a test My name is PYCODESS\n I am a programmer. How do I make a line definition set character limits on each line?
anyway
just split it after ever length?
i believe textwrap is an inbuilt lib doing that
Well if that's ^ your actual question, maybe this helps?
have fun everyone
show traceback
you too
defer the response first
ctx.response.defer()
top of your command logic
how do you do that?
Does anybody here know what Panda meant when he said you can make on_message a listener
@bot_instance.listen("on_message")
async def uwu_on_message_listener(message):
...
''' or '''
@bot_instance.listen()
async def on_message(message):
...
thats how you make listeners
the uwu one is definetly better
@bot_instance doesn't exist
use whatever you have defined your variable
oh
as the instance of a Bot object
lol
and on a side note, you can create multiple listeners for the same event to keep your code organized
import asyncio
@bot_ins.listen("on_message")
async def warn_message(message: discord.Message):
await message.reply("You know what?")
@bot_ins.listen("on_message")
async def see_off_message(message: discord.Message):
await asyncio.sleep(2)
await message.reply("bye")
@bot_ins.listen("on_message")
async def throw_message(message: discord.Message):
await asyncio.sleep(5)
await message.author.kick()
can u give a example for a bot object?
thx
from discord.ext import commands
bot = commands.Bot(command_prefix="uwu", intents=discord.Intents.default())
''' or the subclassed version '''
class MyUwUBot(commands.Bot):
def __init__(self):
super().__init__(command_prefix="uwuwuwu", intents=discord.Intents.default())
async def on_ready(self):
print("uwu")
#you can create more events with just their names (no need for a listener decorator or an event decorator)
Seems correct
put that under warn command
Guys can someone help me make a multi guild welcome system with stuff like this
oh lmao
Hello Frey exact timing
!d discord.on_member_join
discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
Kind of late but why even tho I have done the first version
this pops up
"bot_intents" is not defined
bot_intents isnt defined....
the error pretty much says loud for itself
does anyone know how to do it?
is anyone aware if modals can contain images in the pop-up window?
currently they can only contain small and large text inputs
ok thank you just curious has there been any news when modals will get a new update?
I don't know, maybe ask in the discord developers server: https://discord(dot)gg/discord-developers
Maybe he was just lonely and typed here to get some company
makes me cry
Guys how can we send a error using ctx whenever any error occurs in our project
@commands.command()
async def wm_set(self, ctx):
async with aiosqlite.connect("wm.db") as db:
cursor = await db.cursor()
await cursor.execute("CREATE TABLES IF NOT EXISTS wm(guild_id INTEGER, channel_id INTEGER)")
await db.commit()
await cursor.execute("SELECT channel_id FROM wm WHERE guild_id = ?", (ctx.guild.id)
)``` @slate swan opinions?
would this work
You can use on_command_error event for command related errors (it takes 2 parameters, the Context and the Exception raised).
yes it will work but I suggest adding a comma (,) after ctx.guild.id to make it a tuple -> (ctx.guild.id,)
oh ye i forgot that
since it may cause an error
done
nice
and as I said, create a single connection
multiple connections to a single file could cause errors
if many commands are run at once
a nice chunk of your data could be lost
also, it is CREATE TABLE without the s
pfftt
so like async def setup_db something like that?
you need to call that somewhere, I still recommend to upgrade to v2
Well i mean he can read because he readed the messages in this channel, and he can speak english because otherwise he could not speak with us, so he read the error and there is no way he didn t understand it 
good night
and no comments
this level of understanding is beyond my level of understanding
I wish to sleep but it's 14:04 so i think that i will just take a coffee
Oh you're in Europe, i would've never said it
lol
is it possible to respond to the message that invoked the command?
!d discord.ext.commands.Context.reply
await reply(content=None, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shortcut method to [`send()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.send "discord.ext.commands.Context.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") referenced by this context.
For interaction based contexts, this is the same as [`send()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.send "discord.ext.commands.Context.send").
New in version 1.6.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") or [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") instead of `InvalidArgument`.
thanks
So... The love for the ||shit||?
π€¨
Or the ||shit|| for the wisdom
..
is there a way to set embed image to a local file instead of url?
how to randomly choose 3 item from a list with random
Never studied greek so dunno precisely
library?
discordpy
!d random.shuffle could be
random.shuffle(x[, random])```
Shuffle the sequence *x* in place.
The optional argument *random* is a 0-argument function returning a random float in [0.0, 1.0); by default, this is the function [`random()`](https://docs.python.org/3/library/random.html#random.random "random.random").
To shuffle an immutable sequence and return a new shuffled list, use `sample(x, k=len(x))` instead.
Note that even for small `len(x)`, the total number of permutations of *x* can quickly grow larger than the period of most random number generators. This implies that most permutations of a long sequence can never be generated. For example, a sequence of length 2080 is the largest that can fit within the period of the Mersenne Twister random number generator.
Deprecated since version 3.9, will be removed in version 3.11: The optional parameter *random*.
!e
import random
print(random.choices([1, 2, 3, 4], k=3))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
[4, 1, 3]
Does it repeat ? The numbers
set_image("attachment://image.png") the file has to be in the same dir
nope
!e
import random
print(random.choices([3, 4], k=3))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
[3, 4, 4]
you do know that the list only has 2 items, so it will
use a set and a for loop with the len function
um for loop better lol
its alright the player would love it to repeat anyways
i use for loop
but not in this case
What happened
I just simple remove the item that is appended to a list
!d random.sample
random.sample(population, k, *, counts=None)```
Return a *k* length list of unique elements chosen from the population sequence or set. Used for random sampling without replacement.
Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices).
Members of the population need not be [hashable](https://docs.python.org/3/glossary.html#term-hashable) or unique. If the population contains repeats, then each occurrence is a possible selection in the sample.
oh lol
btw way do u know how to leave a code alive and running on pycharm?
etc not fall asleep
press run π€£
i do and leave it arnd for some time it falls asleep is it due to my computer sleeping?
Goto power options and disable screen time
yeah either set your computer to not go to sleep from the power options
yeah guess i will do that
but when it comes to power saving...better use a vps..
btw
u need to pay every month or just one time
most organizations impose subscription-only schemes, but there are organizations where you can buy servers for lifetime too
alright
Anyone?
Wtf
@slate swan wht?
Indents
I tried
Not working π
Can u paste the code on
Ok
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
reroll [mention a text channel] [id of giveaway]
@slate swan done now?
Is this replit
Just tell me why are you using it (I need it for anonymous social survey)
Anonymous social survey ok
Yes
Is there a way to make it so when a user presses on a hyperlink in an embed it will copy something to their clipboard?
It can only be implemented by the site the hyperlink leads to
is it only me or bot cant use external emoji even if it has that perm
just cuz everyone role is missing that perm
Make sure it has access to the emoji
it has
someone told me its cuz interaction is a webhook
so it uses everyone perm
Make sure you have the emoji's id and name
its working in every other server where everyone role has external emoji perm
u can also try
Is there a way to make on_message event work only in some channels and not in all?
make it id specific
async def on_message(message):
if message.channel.id == ...: ...
or
if message.channel.id in (...): ...```
πi would do the opposite to not care about indentation
async def on_message(msg):
if msg.channel.id not in (enabled_channel_ids): return
# the code
Same
I want whatever the arg is (which I want to use it is as number), to search the file_number and if it finds a result, to send the number
E.g, !insert 611, and the bot to take the 611 number from file_number, and send it
If that number arg is not in the file_number, to answer that this number is not recorded
same
lol
but anyways, there's no point of me making id specific features π
@slate swan is there any way I could have roles and channels mentionable within the same argument?
π lightbulb*
typing.Union
tried that, the command doesnt even show up
mind if i try and tell in a few minutes?
don't have my laptop with me rn
sure, thankee
Tried typing.Any?
wait
i doubt the converter can be able to parse the object
not sure really
is there an event that works when u use a command ?
I doubt it too but it's worth a try
no.
tbh I'd just take a normal string argument and use the roleconverter and textchannelconverter to get the object inside the function
!d discord.ext.commands.on_command
weird
hm I see.....but if I just had to do that, I could ask the user for id
tnx
for file_number, rarity, position in map(lambda x: x.strip('\n').split('\t'), open('rarity_table.txt')
nope, converters can work with name, mentions and IDs, any of them
@plugin.command
@lightbulb.option(name="arg", description="role or channel")
@lightbulb.command("test", "lalalalala")
@lightbulb.implements(lightbulb.PrefixCommand)
async def foo(context: lightbulb.PrefixContext) -> None:
role = await lightbulb.RoleConverter(context).convert(context.options.arg)
channel = await lightbulb.GuildChannelConverter(context).convert(context.options.arg)``` this is functional, tho there should be some way to take Union args
weird, I see
thats how literally every library works...
this is cursed
Ikr, thanks though
elaborate?
it's a creature of demons
for file_number, rarity, position in map(lambda x: x.strip('\n').split('\t')), open('rarity_table.txt'):
print(file_number)```
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: map() must have at least two arguments.
put a ) in the end
average discord.py user running away from decorators.
lol

Why ? I get error when I do that
doesn't discord.py 2.0's application command implementation also require a lot of decorators though
ah wait
for file_number, rarity, position in map(lambda x: x.strip('\n').split('\t'), open('rarity_table.txt'))
like 2 lol
no
Ok thanks, but it doesn't sync with the arg number parameter
not really, from what i see in the examples
ah i didnt read your question, use a database or json for that. .txt is not good for this kind of stuff
I use sqlite db but even with db I don't know how I can sync the number arg parameter with file_number in the db data
...
u can write a query like ("SELECT ... FROM table WHERE arg=?", arg) to get the row from the db
Damn #help-grapes message
3 pings
and its inside a object ```js
{
value: "",
label: "",
description: "",
const mySecret = ""
}
thats your own code.
do u know js?



