#discord-bots

1 messages Β· Page 1068 of 1

scarlet sorrel
#

True

#

@sick birch managed to get this with the inline thing, but why is there such huge space

sick birch
#

Are you using the whitespace hack?

scarlet sorrel
#

yes

sick birch
#

That's probably why

scarlet sorrel
sick birch
#

They weren't meant to use the whitespace hack, gonna have to deal with it

scarlet sorrel
#

if i do it any other way its totally broken

sick birch
#

It's meant to look better when it's used like intended

scarlet sorrel
#

its kinda funny but usless

sick birch
#

Why not have the user's name and discrim as the field name, and their messages as the value?

scarlet sorrel
#

or equally as long

sick birch
#

You don't even need fields, you can fit them all into the description which gives you more flexibility

scarlet sorrel
#

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?

slate swan
#

make only 2 fields both of which are inline

scarlet sorrel
#

thats what that is

slate swan
#

these are 3

sick birch
#

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

scarlet sorrel
#

thats what 2 inline looks like

sick birch
#

Probably better to just use ljust with spaces to put it all in the desc

scarlet sorrel
#

whats ljust

#

you mean subtract length of the current string from the longest string and add that as spaces to the current string

sick birch
#

!e

print("user1#1234".ljust(20, ' ') + ' - ' + '500')
print("user2#5678".ljust(20, ' ') + ' - ' + '250')
unkempt canyonBOT
#

@sick birch :white_check_mark: Your eval job has completed with return code 0.

001 | user1#1234           - 500
002 | user2#5678           - 250
sick birch
#

something like that

scarlet sorrel
#

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')

unkempt canyonBOT
#

@scarlet sorrel :white_check_mark: Your eval job has completed with return code 0.

001 | user1#12dddddddd34   - 500
002 | user2#5678           - 250
jagged adder
#

where do i put this in my code

sick birch
#

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?

jagged adder
#

any of this relevant or not even related

sick birch
#

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:
  ...
jagged adder
#

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

heavy shard
#

is it wait_for("msg" ...) or wait_for("message" ...)?

scarlet sorrel
heavy shard
#

i mean bot.wait_for(event) should event be "msg" or "message" ?

#

i think the latter

jagged adder
#

thats the file

#

i got to go, any thoughts pm me @heavy shard, ill get back to em later

torn sail
#

It’s just the normal event name without on_

stray carbon
#
def draw(self):  # thanks copilot
        match self.tries:
            case 0:
                return """

How to do this in python 3.8

maiden fable
#

What's this...

#

Seems like arcade

stray carbon
#

it returns invalid syntax even when i import Match from typing

maiden fable
slate swan
#

you can't use Match case in 3.8, if elif is ur deal

stray carbon
scarlet sorrel
stray carbon
#

ohh

#

Whats typing.Match then?

slate swan
#

!d typing.Match

unkempt canyonBOT
#

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).
slate swan
#

thats another thing, meant for regex.

stray carbon
#

oh

keen mural
#

how can i put a @commands.cooldown(1, 10, commands.BucketType.user) in an if statement

#

how can i put a cooldown

#

in general

slate swan
#

what do u mean

#
@cooldown(rate, per, bucket)
@command(**kwargs)
async def command_callback(ctx):
   ...
slate swan
keen mural
scarlet sorrel
#

why not make it instant

slate swan
keen mural
#

i mean like if they are missing an argument for example they still get a cd and i dont want that

slate swan
#

it just broke 3 times this week

slate swan
#

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

keen mural
keen mural
#

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

slate swan
#

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

sick birch
#

I'd probably just have a global error handler to handle all the missing argument issues

#

Best not to repeat yourself in your code

keen mural
sick birch
#

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

slate swan
#

or a long elif tree which checks the command names

hollow zealot
#

how do i install dpy2.0 on replit?

lucid lance
#

hello

hollow zealot
#

hi

maiden fable
lucid lance
#

can you learn any type of coding here?

hollow zealot
#

how do i install dpy2.0 on replit?

maiden fable
unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

maiden fable
scarlet sorrel
#

@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("πŸ—‘οΈ")
sick birch
#

Definetely by making all the message #s on the same "column"

scarlet sorrel
#

but the question is how

sick birch
#

Find the largest name. add 5 for #XXXX, set that as the first argument for ljust

slate swan
scarlet sorrel
#

since its pulling all of the info from a huge file

hollow zealot
sick birch
placid verge
scarlet sorrel
#

there's only like 50k messages in there

#

text is very tiny in terms of space

#

computers are good at dealing with it

sick birch
#

just a plain old text file?

scarlet sorrel
sick birch
#

ah, that's very inefficient

scarlet sorrel
#

you dont even wanna know how im saving and deploying it

#

you would probably cry

sick birch
#

so every time there's a new message, you append that to the text file?

sick birch
#

😬

scarlet sorrel
#

just open the entire text file as a string, add the new stuff to the end, then write the entire thing back

sick birch
#

oh my

scarlet sorrel
#

didnt know how to do fancy stuff when i wrote that part of the bot

#

should probably fix it

sick birch
#

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

scarlet sorrel
#

nahhhhh

#

not enough data

#

this way i can have all kinds of fun commands

#

which i already have made

#

this leaderboard one included

sick birch
#

then you might be interested in something like our metricity bot

scarlet sorrel
#

oh nvm

honest laurel
scarlet sorrel
#

it is using append

sick birch
sick birch
slate swan
honest laurel
sick birch
# scarlet sorrel why

it lets us do a lot of very fancy stuff with metrics data, and has user messages in there

honest laurel
#

You don't rewrite full file, so

sick birch
#

It's not just that, it's a plain text file not meant for handling large amounts of data

honest laurel
#

Storing them into a db is obviously a better way to do that

slate swan
#

and large mutations of it!

sick birch
#

We used it frequently to figure out which channels get the most messages, etc

scarlet sorrel
#

where is the actual bot in the repo

sick birch
#

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

scarlet sorrel
#

only 400 lines

honest laurel
scarlet sorrel
#

.js 🀒

honest laurel
#

come on, it's only 100mb

sick birch
#

I'm assuming you're only joking

honest laurel
#

I'm just saying that storing data into plaintext files is ok

sick birch
#

if it's static, never changed, then sure maybe

honest laurel
#

Logging was and is done using files

sick birch
#

if it's dynamic data i would steer clear of it

honest laurel
#

append only should be fine too

sick birch
#

using text files isn't all that much of an improvement from JSON

scarlet sorrel
honest laurel
#

It is an improvement

sick birch
#

since you can append, it's a little bit of one

scarlet sorrel
#

wow

sick birch
#

still vulnerable to the other flaws

scarlet sorrel
#

im ahead of the game then

honest laurel
#

Json files in 99% of cases should be fully overwritten

scarlet sorrel
#

i have no clue how to use JSON files

#

text files are easy

honest laurel
#

And you can corrupt your file this way unless you do some kind of atomic write

slate swan
scarlet sorrel
slate swan
#

then its easy

honest laurel
#

@scarlet sorrel I think you can learn sql and store your messages there (in case you need to access them later)

sick birch
#

best choice

honest laurel
#

If you just want a log - text file should be fine

honest laurel
#

literally

scarlet sorrel
#

i can just read the file

honest laurel
#

access them in efficient manner

sick birch
#

you don't need to store message content, only other metadata like things such as user ID, channel ID, guild ID, etc

slate swan
#

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

scarlet sorrel
slate swan
honest laurel
scarlet sorrel
slate swan
scarlet sorrel
#

its not against tos

honest laurel
#

oh, nvm actually

slate swan
honest laurel
slate swan
scarlet sorrel
#

my bot probably breaks every rule of the discord TOS in some way anyway

slate swan
#

nice bot

scarlet sorrel
#

i know it breaks this servers rules or whatever

sick birch
slate swan
slate swan
scarlet sorrel
honest laurel
sick birch
# slate swan as in?

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

slate swan
slate swan
sick birch
#

Since it's been vetted by discord officially, and not some random bot that's going to get shut down in 2 weeks

slate swan
scarlet sorrel
keen mural
#

how does a bot get verified

slate swan
#

its their app after all

slate swan
slate swan
scarlet sorrel
keen mural
#

ok

sick birch
slate swan
#

hm inarguable

scarlet sorrel
#

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

sick birch
#
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

scarlet sorrel
#

i do things manual

sick birch
scarlet sorrel
#

πŸ§‘β€πŸŒΎ

scarlet sorrel
#

its just Unicode data

#

dont be scared lol

honest laurel
#

@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

sick birch
#

not much experience with sqlalchemy. I usually work with Prisma (the typescript client, not the python one)

#

but yeah, similar concept

honest laurel
#

It's hard to use something like prisma after sqlalchemy tbh πŸ˜…

scarlet sorrel
#

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
sick birch
#

could really do with some seperation of concerns

scarlet sorrel
#

but m o u n t a i n

honest laurel
#

import datetime as etad

scarlet sorrel
honest laurel
#

just import datetime 🀷

scarlet sorrel
#

no

#

you cant

honest laurel
#
import datetime

now = datetime.datetime.now()
slate swan
#

huh? why not

scarlet sorrel
#

dude you cant

honest laurel
#

You can

scarlet sorrel
#

datetime overlaps with datetime

#

you cant just import datetime

honest laurel
slate swan
#

so? just use datetime.datetime.now()

scarlet sorrel
#

you cant

slate swan
#

datetime is a class

scarlet sorrel
slate swan
#

!e py import datetime print(datetime.datetime.now())

unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

2022-05-28 05:57:02.027491
scarlet sorrel
#

datetime overlaps with datetime

slate swan
#

datetime(module).datetime(class)

scarlet sorrel
#

you are only importing datetime

honest laurel
#

!e

import datetime

now = datetime.datetime.now()
print(now)
print(datetime, datetime.datetime)
unkempt canyonBOT
#

@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'>
slate swan
honest laurel
scarlet sorrel
jade tartan
#

Someone

scarlet sorrel
#

trust me it causes errors

honest laurel
scarlet sorrel
honest laurel
#

😐

scarlet sorrel
#

forget it jesus

slate swan
scarlet sorrel
#

you guys never had to work with time very much

honest laurel
scarlet sorrel
#

yes

honest laurel
#

ok

slate swan
#

am not saying it doesnt work, but as per the pep8 standards, thats incorrect.

honest laurel
#

How do you guys deploy discord bots?

maiden fable
honest laurel
#

I mean the process itself

maiden fable
#

Ah

#

python bot.py

slate swan
#

and a shell command as hunter mentioned forsure

#

guys Please guide me about hosting

plucky flower
#

Can anyone tell me how to code python

#

I am totally new at all,,know nothing

slate swan
#

Ya

slate swan
#

Please

#

Am New to bots hm πŸ™‚

#

@slate swan Have you attended AWS Summit

#

It's great

#

for AI

slate swan
slate swan
#

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

onyx marten
#

Hello Im Here To Help With Assignments And Etc! Dm For Help

slate swan
#

Can you please recommend an IDE for python?

slate swan
slate swan
onyx marten
#

No I Mean Teaching!

dusky pine
onyx marten
#

not helping

slate swan
slate swan
dusky pine
#

LOLL

slate swan
dusky pine
#

it was a joke, of course it's just x = 4

slate swan
#

Or VS2022

slate swan
onyx marten
#

im sorry

slate swan
#

Visual Studio Code is not so heavy

#

its like 42mbs of ram

onyx marten
#

im trying my best to get helpers badge so i can teach people!

slate swan
#

compared to pycharm which is 1200gb of ram

slate swan
honest laurel
slate swan
#

nice

slate swan
onyx marten
#

Well then how do i get it

dusky pine
#

you have to be actively helping

slate swan
#

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

slate swan
#

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

slate swan
honest laurel
#

You can check where command was executed

slate swan
#

ctx.channel.id?

#

the channel/guild where the command was invoked?

#

3 pings😭

honest laurel
slate swan
slate swan
slate swan
slate swan
#

haven't learned them nor used them😭

honest laurel
#

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"]
slate swan
#

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

honest laurel
#

Can't you right click and copy id?

slate swan
honest laurel
#

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)
slate swan
#

turn on developer options, you can hold on the channel and use Copy ID

honest laurel
#

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

slate swan
#

a tablet and a phone have the same client lol

honest laurel
#

Did you enable developer mode?

slate swan
#

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

unkempt canyonBOT
#

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...
slate swan
#
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

unkempt canyonBOT
#

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").
slate swan
#

you can use any of these kwargs

slate swan
slate swan
slate swan
#

agreed

#

you need to start the task using auto_send.start() as well

stone beacon
#

ahh lovely it works

#

Screw nitro, all my homies got empty wallets

slate swan
#

wait before the bot is ready using the wait_until_ready method at the top of the task and start the task

stone beacon
slate swan
stone beacon
#

πŸ˜‚

slate swan
#

i told-

honest laurel
#

900 loc

slate swan
honest laurel
#

add 1 space

slate swan
slate swan
honest laurel
#
async def example():
    await a()
   await b()
slate swan
#

@honest laurel can you explain?

#

what/

honest laurel
slate swan
#

nope still not working

#

Replit?

#

It usually causes poor intendation, use a real ide, fix the indents and paste it back

slate swan
oak warren
honest laurel
#

Send it

slate swan
#

done

vale wing
# slate swan

Replit sucks at indents also why are you even using it? Personal preference or seen it in the tutorials

slate swan
#

🧒

vale wing
#

And yeah following naming convention: lowerCamelCase is not for python at all (UpperCamelCase is used in classes), use snake_case for variables

vale wing
#

Mention and cap emoji doesn't answer it anyhow

slate swan
#

tutorial indeed

vale wing
#

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)

slate swan
honest laurel
#

It's hard to go back to anything else if you used a good IDE for a while

slate swan
honest laurel
#

I personally use PyCharm because i use a lot of built-in features, VSCode is quite good too

slate swan
#

vs code extensions

honest laurel
#

It's not the same πŸ˜‰

slate swan
#

im saying that vs code extension feature

rain olive
slate swan
honest laurel
vale wing
slate swan
#

imagine using mobile ide

vale wing
#

Pycharm professional feels very uh professional

slate swan
#

huh

honest laurel
slate swan
#

Pycharm is good but vs code is love

#

Notepad >>>

slate swan
#

word pad better

#

just code and copy paste

vale wing
#

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```
honest laurel
vale wing
#

Maybe

#

But like it's none only in init

honest laurel
#

mypy deprecated implicit Optional | None

honest laurel
regal pulsar
vale wing
#

πŸ₯²

slate swan
honest laurel
#

Any typechecker would complain about it

regal pulsar
#

lmao

honest laurel
slate swan
slate swan
slate swan
#

raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'member_count@honest laurel

slate swan
#

it's a property of discord.Guild

#

!d discord.Guild.member_count

unkempt canyonBOT
#

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]`.
slate swan
slate swan
slate swan
#

lol

#

Wrong channel (or server..?) I guess

slate swan
slate swan
#

Lmao

regal pulsar
slate swan
#

woah discord is offering nitro for free again

slate swan
#

Anyone here who is extremely experienced with working with discord api, kindly drop me a message

#

Im looking to engage someone

#

extremely experienced

placid skiff
#

Extremely uwu

regal pulsar
#

lmao

slate swan
glass tangle
#

aside from the fact I'm not getting engaged today, I don't think I'm experienced enough

slate swan
#

am I the only one who misread that question or.....

regal pulsar
#

we all did i think

slate swan
west wigeon
#

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"

slate swan
#

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...

#

pWut and i believe that most of the regulars here are no copy pasters

west wigeon
#

good to hear

tropic burrow
#

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)
       ```
slate swan
#

try it and see,.... json is really unpredictable

tropic burrow
#

nothing happened

#

no errors

slate swan
#

πŸ˜”

#

why would you do this lmao

tropic burrow
#

idk how to do it with replit

slate swan
#

use sqlalchemy instead

slate swan
slate swan
slate swan
#

+1 this

west wigeon
#

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.

slate swan
#

according to pep8 standards naming should make sense

west wigeon
#

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.

honest laurel
#

(If used correctly)

west wigeon
#

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

honest laurel
#

Hah, yeah, files are unreliable

west wigeon
#

(from examining that code excerpt the author probably isn't ready for databases yet)

west wigeon
#

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.

silk fulcrum
#

How can I install dpy2.0?

#

(im banned from dpy server)

hazy schooner
#

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

silk fulcrum
honest laurel
#

pip install git+https://github.com/Rapptz/discord.py.git

silk fulcrum
#

thx

slate swan
slate swan
#

good

silk fulcrum
#

avatar_url = avatar.url

#

xD

slate swan
silk fulcrum
#

should I list everything?

slate swan
#

no thanks

#

im dumb

silk fulcrum
#

stupid pycharm... for what did i upgrade

misty stream
#

little question can you get a cog function in the main.py file ?

#

if yes how ?

weak moat
#

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

glass tangle
#

what would be involved in the calculation?

weak moat
#

this is coin = ['PENTA', 'SPARK', 'PLYUM', 'TEPLOTA']

#

and the value variable specified by the user

#
if value == coin:
weak moat
glass tangle
#

let's take one of the coins... which one?

weak moat
#

SPARK

glass tangle
#

ok, what do you know about a SPARK?

weak moat
#

in what sense?

glass tangle
#

how about, in the same sense as you want to do this calculation

#

what are the instructions telling you?

weak moat
#

Let's make it easier.
How do I check if a user-entered value variable is in the list coin = ['PENTA', 'SPARK', 'PLYUM', 'TEPLOTA']

weak moat
#

I'll try it now

glass tangle
#

let's go back to the spark coin... what are all the things you know about it?

weak moat
slate swan
#

welcome

slate swan
glass tangle
#

let's start with this calculation... what would the calculation do?

slate swan
#

....?

weak moat
slate swan
#

lmao

glass tangle
#

are there instructions?

slate swan
#

....

glass tangle
#

do the instructions say: "calculate the number of coins"?

weak moat
#

jimm already helped me, you don't have to break your brain

glass tangle
#

if there are no instructions, I don't understand the purpose of the exercise?

#

if there -are- instructions, what are they?

shrewd apex
#

πŸ‘€

weak moat
glass tangle
#

me? sorry, I've not worked with it before

slate swan
weak moat
#

how to make text not go out of bounds?

glass tangle
#

how do you measure the bounds?

warped mirage
#

Guys can someone tell me what could I add as a premium feature for premium bot , Idk what would be good to add

slate swan
#

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

slate swan
weak moat
#

text_body = f"""{DESCRIPTION}"""
this is my text

glass tangle
#

you might want to think about this problem, how would you know a letter of a particular size would fit into an area?

slate swan
weak moat
#
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?

slate swan
#

hm set the margin and offset as necessary

warped mirage
slate swan
#

and the width

weak moat
#

okay

glass tangle
#

find or invent somethign that someone else would want to buy

slate swan
warped mirage
#

Hmm true

weak moat
warped mirage
#

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

shrewd apex
glass tangle
#

what are the -units- of the size of the image?

shrewd apex
maiden fable
#

Pixels?

glass tangle
#

sure, that is one possible unit. and,

shrewd apex
#

pil only works with pixels as far as i know

glass tangle
#

if you see an image, how else can you mesure it? what other units are there?

shrewd apex
glass tangle
#

ohhh, another unit is cm!

tight mica
#

name = int(user) this is what you are doing

shrewd apex
#

u can use ctx.author.mention

glass tangle
#

so, you can find out how wide an image is, -in CM-, ahd how high that image is, also -in CM-

shrewd apex
tight mica
glass tangle
#

so, then you will know the size of the image in cm

shrewd apex
slate swan
shrewd apex
#

only in description and values

tight mica
#

not in field name too right?

shrewd apex
shrewd apex
#

u should try to focus and narrow down to a topic

glass tangle
#

@slate swanbecause you want to know if a string of characters will fit in the image

slate swan
shrewd apex
tight mica
#

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

slate swan
#

Still it feels a lot limited... I mean ofc discord isn't a development or gaming site but a chat service anyways

glass tangle
#

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?

shrewd apex
#

there might be a few limitations in the api but it's more than enough to support ur imaginations

tight mica
#

what module are you using to -render- text

shrewd apex
tight mica
#

ye

glass tangle
#

@slate swanthe point is, how will you know if a string of characters will fit on an image

tight mica
#
draw = ImageDraw.Draw(bgimage)
draw.textsize(string, font) # returns a tuple with w, h```
then check if its larger than the main bg image
slate swan
shrewd apex
#

u can basically take the font size which is in pixels

#

and then check len of string

#

multiply...

tight mica
slate swan
regal pulsar
#

lmao

glass tangle
#

are all the characters in the font the same width?

regal pulsar
#

time to make a meme bot for the 387547th time

slate swan
#

Make a dashboard music player to control your bot's music from site/app

shrewd apex
slate swan
shrewd apex
#

there will always be people to follow suit

regal pulsar
tight mica
regal pulsar
#

🫠

shrewd apex
#

so what u need is to be unique and a smash at the same time so that others don't stand a chance

tight mica
# tight mica depends on the font

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
glass tangle
#

@tight micayes. AND it depends on the -size- of the font too

slate swan
regal pulsar
#

like ydgrassil

#

its userphone is really cool

slate swan
shrewd apex
slate swan
#

or just use the brave browser

regal pulsar
shrewd apex
#

the ads are on the client side

slate swan
regal pulsar
shrewd apex
#

yeah

regal pulsar
#

i see

shrewd apex
#

downloads are on server side so no way arnd that

unkempt canyonBOT
#

7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.

regal pulsar
#

;/

glass tangle
#

@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

slate swan
#

wtf is - word -

#

in cm?

tight mica
slate swan
#

centimetres

glass tangle
#

@slate swanextra emphasis

slate swan
#

uhuh

tight mica
#

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

slate swan
shrewd apex
#

what's the default size or a full scale size of an embed image again

glass tangle
#

it could

slate swan
#

sizes remain constant iirc

glass tangle
#

that's why you need the size of the rendered string

shrewd apex
#

only ur screen size changes 😎

slate swan
#

Nah there's smaller pixels too

#

yes

shrewd apex
slate swan
#

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?

tight mica
#

zoom levels 😐

slate swan
#

^

glass tangle
#

good... I think you get this idea

#

this is an example of how you need to be able to think

shrewd apex
#
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.
slate swan
shrewd apex
#

ok back to topic

vocal plover
shrewd apex
#

before someone rule7 us

tight mica
#

are we going off topic

#

oh u already mentioned

shrewd apex
#

lmao

glass tangle
#

I guess text strings and their size when rendered, is off the topic of discord bots?

tight mica
#

because they went to the visible size

#

not their pixel size

glass tangle
#

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

tight mica
#

not possible if CM = centimetre

shrewd apex
#

lmao u take a joke too hard

weak moat
#

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?

glass tangle
#

anyway

slate swan
#

just split it after ever length?

shrewd apex
#

i believe textwrap is an inbuilt lib doing that

slate swan
glass tangle
#

have fun everyone

slate swan
#

show traceback

slate swan
#

defer the response first

#
ctx.response.defer()
#

top of your command logic

wet crystal
#

how do you do that?

#

Does anybody here know what Panda meant when he said you can make on_message a listener

slate swan
wet crystal
slate swan
#

indeed

#

yes

slate swan
wet crystal
#

oh

slate swan
#

as the instance of a Bot object

wet crystal
#

lol

slate swan
#

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()
wet crystal
#

can u give a example for a bot object?

slate swan
# wet crystal can u give a example for a bot object?
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)
maiden fable
#

Seems correct

paper sluice
#

put that under warn command

warped mirage
#

Guys can someone help me make a multi guild welcome system with stuff like this

#

oh lmao

#

Hello Frey exact timing

unkempt canyonBOT
#

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.
warped mirage
#

I know that but I must add a I’d for a channel

#

Idk how to make it multi guild

wet crystal
slate swan
#

the error pretty much says loud for itself

warped mirage
#

does anyone know how to do it?

ashen perch
#

is anyone aware if modals can contain images in the pop-up window?

winged bone
ashen perch
#

ok thank you just curious has there been any news when modals will get a new update?

winged bone
#

I don't know, maybe ask in the discord developers server: https://discord(dot)gg/discord-developers

placid skiff
robust fulcrum
#

Guys how can we send a error using ctx whenever any error occurs in our project

warped mirage
#
@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

visual island
#

You can use on_command_error event for command related errors (it takes 2 parameters, the Context and the Exception raised).

slate swan
warped mirage
#

oh ye i forgot that

slate swan
#

since it may cause an error

warped mirage
#

done

slate swan
#

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

visual island
#

also, it is CREATE TABLE without the s

slate swan
#

pfftt

warped mirage
slate swan
placid skiff
# slate swan makes me cry

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 D_D

slate swan
#

and no comments

#

this level of understanding is beyond my level of understanding

placid skiff
#

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

slate swan
#

lol

placid skiff
#

Or in Africa...

#

Good Phx_PepoLMAO

wet crystal
#

is it possible to respond to the message that invoked the command?

placid skiff
#

!d discord.ext.commands.Context.reply

unkempt canyonBOT
#

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`.
wet crystal
loud junco
#

i thought u criticise 24-hour format

#

🀣

#

ashley's philosophy

#

:kekw:

placid skiff
#

So... The love for the ||shit||?

slate swan
#

🀨

placid skiff
#

Or the ||shit|| for the wisdom

slate swan
#

..

ripe blaze
#

is there a way to set embed image to a local file instead of url?

loud junco
#

how to randomly choose 3 item from a list with random

placid skiff
#

Never studied greek so dunno precisely

ripe blaze
#

discordpy

loud junco
placid skiff
unkempt canyonBOT
#

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*.
slate swan
unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

[4, 1, 3]
slate swan
#

Wow great

#

Now I'll add k instead of a for loop

#

πŸ’€

slate swan
slate swan
slate swan
#

!e
import random

print(random.choices([3, 4], k=3))

unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

[3, 4, 4]
slate swan
#

@slate swan 🀨

#

#bot-commands <- dont spam commands

slate swan
#

use a set and a for loop with the len function

#

um for loop better lol

loud junco
#

its alright the player would love it to repeat anyways

#

i use for loop

#

but not in this case

maiden fable
#

What happened

slate swan
shrewd apex
unkempt canyonBOT
#

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.
slate swan
#

oh lol

shrewd apex
#

btw way do u know how to leave a code alive and running on pycharm?

#

etc not fall asleep

loud junco
shrewd apex
#

i do and leave it arnd for some time it falls asleep is it due to my computer sleeping?

slate swan
#

Goto power options and disable screen time

slate swan
shrewd apex
#

yeah guess i will do that

slate swan
#

but when it comes to power saving...better use a vps..

loud junco
slate swan
slate swan
#

Anyone?

#

Wtf

#

@slate swan wht?

#

Indents

#

I tried

#

Not working πŸ˜‚

#

Can u paste the code on

#

Ok

#

!paste

unkempt canyonBOT
#

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.

slate swan
#

Here

#

Wht is this?

#

pastebin

#

πŸ’€

#

Ok

celest remnant
#

anyone knows how to use this command?

ripe blaze
#

reroll [mention a text channel] [id of giveaway]

slate swan
#

@slate swan done now?

heady sluice
slate swan
#

@heady sluice server?

#

@slate swan now what bruh

#

Sparky ded πŸ˜‚

vale wing
#

Just tell me why are you using it (I need it for anonymous social survey)

slate swan
vale wing
#

Yes

ripe blaze
#

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?

vale wing
spring verge
#

is it only me or bot cant use external emoji even if it has that perm

#

just cuz everyone role is missing that perm

dapper cobalt
spring verge
#

someone told me its cuz interaction is a webhook

#

so it uses everyone perm

dapper cobalt
spring verge
#

u can also try

vapid grove
#

Is there a way to make on_message event work only in some channels and not in all?

slate swan
#
async def on_message(message):
    if message.channel.id == ...: ...

    or 
    
     if message.channel.id in (...): ...```
slate swan
#

πŸ˜”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
maiden fable
#

Same

slate swan
#

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

slate swan
#

lol

#

but anyways, there's no point of me making id specific features πŸ˜”

slate swan
#

@slate swan is there any way I could have roles and channels mentionable within the same argument?

#

πŸ˜” lightbulb*

#

typing.Union

slate swan
#

mind if i try and tell in a few minutes?

#

don't have my laptop with me rn

#

sure, thankee

placid skiff
#

Tried typing.Any?

slate swan
#

wait

slate swan
#

not sure really

#

is there an event that works when u use a command ?

placid skiff
#

I doubt it too but it's worth a try

slate swan
#

tbh I'd just take a normal string argument and use the roleconverter and textchannelconverter to get the object inside the function

placid skiff
slate swan
#

weird

slate swan
slate swan
paper sluice
slate swan
#
@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
slate swan
slate swan
slate swan
heady sluice
#

it's a creature of demons

slate swan
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: map() must have at least two arguments.

paper sluice
#

put a ) in the end

slate swan
paper sluice
#

lol

heady sluice
slate swan
vocal snow
paper sluice
#

ah wait

for file_number, rarity, position in map(lambda x: x.strip('\n').split('\t'), open('rarity_table.txt'))
slate swan
slate swan
paper sluice
slate swan
vocal snow
#

...

slate swan
paper sluice
slate swan
#

3 pings

#

and its inside a object ```js
{
value: "",
label: "",
description: "",

const mySecret = ""
}

#

thats your own code.

paper sluice
#

do u know js?