#discord-bots

1 messages · Page 68 of 1

wicked atlas
#

Should be fine, as long as you aren't trying to serve to thousands of userss

wild spoke
#

Wanting to assemble a compact server

wicked atlas
#

gee?

wild spoke
#

Ye

#

How much memory will it consume?

#

If rpi only has one gig

wicked atlas
#

depends

#

If the bot has to cache a lot of users/channels/guilds and stuff like that, then it might use a fair chunk of memory

wild spoke
#

That's why I was thinking about jsons

wicked atlas
#

Not to mention python isn't the most memory efficient language out there

wild spoke
#

Less ram, more space

wicked atlas
wild spoke
#

I have no idea how to code on java

wild spoke
wicked atlas
#

Ehhhhh, that still wouldn't improve your memory efficiency

#

probably would make things slower, since you would have to load the entire file into memory to read and write from it

wild spoke
#

💀

wicked atlas
#

The bot has it's own internal cache where it stores user/chanels/message/guild objects

wild spoke
#

I need to build a server...

wicked atlas
#

How many users does your bot have right now?

wild spoke
#

Around 700

#

Three servers

#

But It does not store any per-server data

wicked atlas
#

Well, I don't think it should use too much more memory

#

But I would highly suggest running it on something with a little more than 1gb

wild spoke
#

I have no hardware to run 24/7

#

Using little to no power and absolutely silent

wicked atlas
#

Then I guess stick with what you got until you do

wild spoke
#

Also

#

How does per server moderation work?

#

Mutes, bans, warns stack in one database for all servers?

wicked atlas
#

I'd say when a mute or ban is stored, that guild id is also stored along with it, so that it can be associated with that server

#

There's many ways you could structure your database tbh

wild spoke
#

Still, I have no idea how databases work

#

I think like spreadsheets

#

In excel

wicked atlas
#

Databases like sqlite are similiar to spreadsheets, yes, in that they have columns and rows. Each column has a name, and a specific type of value it's expecting in it. You can add a row to the database, which contains actual data, corresponding to each of the columns

verbal vapor
#

Are there any Verification Bots that use FB group membership to verify?

wicked atlas
#

But with databases, you can do much more complex querries, and it's easier to move around and sort through data quicker

wild spoke
#

Thanks for explaining

sick birch
#

me when almost an hour with no messages

primal token
#

ok

wild spoke
#

Why it's shown that "client" is used here

#

But does not here

patent lark
#

🤔

glad cradle
#

why you're calling a Bot client? I mean client = commands.Bot(...)

patent lark
#

yeahh^

sick birch
#

Also you’re aware that get prefix is called each message?

#

Opening and closing a file each message is perhaps not the best idea

#

especially when it’s blocking

wild spoke
#

dunno

#

all tutorials do it like that

#

and it works

#

and for me it returns keyerror: "(id)"

slate swan
#

Because you get endlessly criticized by others for doing so

wild spoke
#

but why exactly

slate swan
#

There's no harm whatsoever, I don't know where or why this useless convention started

wild spoke
#

anyways

#

are there any good discord bot writing guides

#

cuz documentation is for big brain

slate swan
#

But I don't know of any good guides as I haven't encountered any

#

All the guides I've come across as I was starting out were all terrible

wild spoke
#

first of all I need to know how to use sqlite to store bans, warns and mutes (with timer)

#

and literally there are no guides

slate swan
#

For that you will need to refer to sqlite documentation

wild spoke
slate swan
#

sqlite isn't specifically made for another library (like discord.py or something). you will need to understand how both work and then make them work together

#

you can save yourself time by googling things instead of asking questions in a discord channel.

#

this channel is better suited for getting help regarding niche things or if you don't know where or how to start

#

getting better at doing your own research is a very useful skill in programming.

wild spoke
#

ok how to make a autoresponse cog?

slate swan
#

just my two cents.

slate swan
#

can you elaborate?

wild spoke
#

a cog with functions that auto-respond to messages containing something exact

#

like image, text or emoji

#

basically, can I use event outside the main file?

slate swan
#

!d discord.ext.commands.Cog.listener

unkempt canyonBOT
#

classmethod listener(name=...)```
A decorator that marks a function as a listener.

This is the cog equivalent of [`Bot.listen()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen").
wild spoke
#

yes I noticed in my frankenstein bot

#

but did not figure out how it works

#

can I setup cog commands only in specific channel(-s)?

slate swan
#

You can use this decorator to register event listeners. Here's an arbitrary example for checking message content

class MyCog(commands.Cog):
  @commands.Cog.listener()
  async def on_message(self, message):
      if message.content == 'hi':
          message.channel.send('hello')
slate swan
#

This will send "hello" in the chat whenever someone says "hi"

wild spoke
#

and I can setup via sqlite custom responses?

slate swan
#

Yes, but I don't use sqlite so I can't show an example.

#

You will have to do your own research or ask someone else for that :)

wild spoke
#

oh golly

#

here goes my mediocre 1st university course of python

#

thanks tho

slate swan
#

👍

#

sorry i can't use emotes

wild spoke
scarlet aurora
#

I want to make it so that you can reply to the bot and it recognises it and then sends a message, can I do this in 1.7.3 d.py

obtuse imp
#

i don’t wanna interrupt- but it should be quick- how do you get the current guild the user uses a command in? a link to the docs is fine

scarlet aurora
#

ctx.guild

obtuse imp
#

I take it interaction.guild would work the same?

scarlet aurora
#
    @commands.command()
    async def guild(self, ctx):
        await ctx.send(ctx.guild)```
scarlet aurora
scarlet aurora
#

u can do whatever u want with it, store it, print it

obtuse imp
#

thanks- sorry

scarlet aurora
#

whatever u need it for

obtuse imp
#

Should’ve been able to figure that out myself lmao- but thank you so much ^^

scarlet aurora
#

no need to thank me

obtuse imp
#

eh, I will anyway <3

scarlet aurora
#

I'm just here because I feel like eating rocks with how hard d.py 2.0 is

#

so I'm sticking with 1.7.3

slate swan
#

!d discord.Message.reference

unkempt canyonBOT
#

The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.

New in version 1.5.

slate swan
#

I think this is what you're looking for

#

@scarlet aurora can you explain what you mean a little more?

#

are you talking about wait_for()?

scarlet aurora
#

I think

#

it waits for a response so u can reply to the message?

slate swan
#

!d discord.Client.wait_for (or this?)

unkempt canyonBOT
#

wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
slate swan
#

Still a thing

scarlet aurora
scarlet aurora
#

@slate swan await self.bot.wait_for('message', check=check) works but is there a reply for this?

slate swan
#

reply?

scarlet aurora
slate swan
#

if you want to reply to a message you should pass the message as the reference key-word argument to .send()

#

here's the docs for that method:

#

!d discord.abc.Messageable.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
sick birch
#

!d discord.Message.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 [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message").

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

shortcut

slate swan
#

well the .send() allows you to pass partial messages or message references

#

if message.reply works for you then great 👍

sick birch
#

true, but if you're doing a wait_for you're probably getting a full message obj so might as well use it

slate swan
#

ok fair

cold sonnet
#

can you subclass aiohttp.ClientSession without ClientSession subclass object has no attribute '_connector'

slate swan
#

ot but ClientSession strictly does not support subclassing

#

you should have gotten a warning

wary crystal
#

You'd be better off making a class to encapsulate a session rather than sub-classing ClientSession directly.

cold sonnet
#

it was 6 years ago

#

seemed like a W to try something like this

slate swan
#

subclassing is deprecated though

slate swan
#

i can't visualize this

cold sonnet
#
Traceback (most recent call last):
  File "c:\.vscode\Brala\Test.py", line 17, in <module>
    asyncio.run(main())
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 647, in run_until_complete
    return future.result()
  File "c:\.vscode\Brala\Test.py", line 11, in main
    rjson = await client.get_player_data(id)
  File "c:\.vscode\Brala\wrapper\brala.py", line 8, in get_player_data
    response = await self.get(f"https://api.brawlhalla.com/player/{id}/stats?api_key={self._key}")
  File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\aiohttp\client.py", line 380, in _request
    if self.closed:
  File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\aiohttp\client.py", line 963, in closed
    return self._connector is None or self._connector.closed
AttributeError: 'BHClientSession' object has no attribute '_connector'
Exception ignored in: <function ClientSession.__del__ at 0x00000224F6C10B80>
Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\aiohttp\client.py", line 326, in __del__
  File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\aiohttp\client.py", line 963, in closed
AttributeError: 'BHClientSession' object has no attribute '_connector'
slate swan
#

Can you show some code?

cold sonnet
#

I could just make a new aiohttp.ClientSession everytime when making a call

#

but isn't that unfunctional

slate swan
#

unfunctional?

cold sonnet
#
import aiohttp

class BHClientSession(aiohttp.ClientSession):
    def __init__(self, api_key):
        self._key = api_key

    async def get_player_data(self, id: int):
        response = await self.get(f"https://api.brawlhalla.com/player/{id}/stats?api_key={self._key}")
        return await response.json()

slate swan
#

you aren't calling super().__init__()

cold sonnet
#

now wait a minute

slate swan
#

still, it's not recommended to subclass it

#

just add it as an attribute

cold sonnet
#
import aiohttp

class BHClient():
    def __init__(self, api_key):
        self._key = api_key

    async def get_player_data(self, id: int):
        async with aiohttp.ClientSession() as session:
            response = await session.get(f"https://api.brawlhalla.com/player/{id}/stats?api_key={self._key}")
            return await response.json()

#

I meant this before

#

it's not practical is it

slate swan
#

instead of a creating a new session every time you can just create it once and re-use it

#

also i don't understand why you want to create it manually if you're only using it once and then disposing of it. just use aiohttp.request

cold sonnet
#

so I add it as an argument to __init__ you said

#

no you didn't what the heck am I thinking

#

you said attribute

slate swan
wary crystal
#

You wanna be careful when constructing a new ClientSession inside of non-async functions.

#

ClientSession uses get_running_loop and that'll raise a RuntimeError when no loop is running

slate swan
#

yes, i was going to get to this. it's fine as long as the event loop doesn't change

torn sail
cold sonnet
#

no I wanna reuse it

slate swan
#

aiohttp documentation is hot garbage, i struggle to use it

wary crystal
#

This is very simple to do with hasattr

cold sonnet
#

I'll try, wait a minute

#

where do I store the session then, in an attr?

pliant gulch
torn sail
wary crystal
slate swan
wary crystal
#

Then, inside of your request method, call this before hand to ensure self.session is defined

cold sonnet
#

so now I did this

wary crystal
#

Optionally, you can do the hasattr check inside of your requesting method directly, but that's just a minor optimisation.

cold sonnet
#

I got the json

slate swan
cold sonnet
#

after a couple of seconds I got this

slate swan
#

just create a single request method like so:

import aiohttp

class BHClient():
    def __init__(self, api_key):
        self._key = api_key
        self._session = None
  
    async def _request(self, method: str, url: str, ...):
        if self._session is None:
            self._session = aiohttp.ClientSession(...)
        
        resp = await self._session.request(method, url, ...)
        # do something with "resp"
        return ...
      
    def get_player_data(self, id: int):
        return self._request(f"https://api.brawlhalla.com/player/{id}/stats?api_key={self._key}")
#

that way you also have DRY code

#

(Don't Repeat Yourself)

wary crystal
#

This'll work great yea. Although I have qualms with setting _session as None (typehinting hell)

slate swan
#

it should be fine, there's a type-guard

wary crystal
#

That's why I usually gravitate towards the hasattr method

slate swan
#

hasattr is terrible for type-hinting

#

i mean it works but it's built to be dynamic

wary crystal
slate swan
#

i don't see why you would need to

wary crystal
#

I'm gonna assume that your making a class not just for one endpoint? Otherwise the practically goes out the window

#

Or maybe you'd want to access it later by yourself, etc.

cold sonnet
#

excuse me what

slate swan
#

can someone tell me why this wont work

cold sonnet
#

oh this happens just once the code ends so it's not really harmful

pliant gulch
cold sonnet
#

no

#
import asyncio
import datetime
import json

from wrapper import brala

client = brala.BHClientSession(key)

async def main():
    id = 24737524
    await client.create_session()
    rjson = await client.get_player_data(id)
    with open(f"stats-{id}-{datetime.datetime.utcnow().timestamp()}.json", "w") as f:
        f.write(json.dumps(rjson, indent=2))

    await asyncio.sleep(3)

asyncio.run(main())
pliant gulch
#

Maybe use some temp measure ```py
while not client.closed:
await asyncio.sleep(0)

#

I wouldn't keep this in production code though

cold sonnet
#

or just

#

close the client

slate swan
#

Can someone help please!

#

Read the roar

pliant gulch
slate swan
#

Error*

cold sonnet
#

I'm just testing what I currently have

#

everything's gonna change here eventually

#

the only thing I need now is different functions for different requests

slate swan
slate swan
pliant gulch
#

So you don't make people manually close the client rather ```py
async with Client() as client:
return await client.request(...)

cold sonnet
#

but I wanna reuse the client

pliant gulch
cold sonnet
#

oh

pliant gulch
#
async with Client() as client:
    await client.request(...)
    await client.request(...)
    await client.request(...)
    return await client.request(...)
#

Within the context manager the client is re-usuable

#

It just closes when it exits the context manager

cold sonnet
#

makes sense, unfortunately that's not what I meant

#

later I'm gonna use this API wrapper alongside with discord.py

#

and I'll want to use the same session with for example a command

#

that's used multiple times

wary crystal
#

The context manager andy said is optional to use

#

Meaning you can have both the context manager way and the normal way

pliant gulch
unreal siren
#

Hey guys for some reason my bot is sending 2 messages at once and i've noticed that the first message isn't even in the code but it was there before i saved and the 2nd one is the message after i saved

cold sonnet
unreal siren
#

i did

#

i even restarted the server

ocean geyser
#

where can someone help me with my code?

cold sonnet
cold sonnet
ocean geyser
cold sonnet
#

yes

unreal siren
ocean geyser
#

for this i need help

cold sonnet
#

oh that's interesting

cold sonnet
ocean geyser
#

does it work?

#

but its work?

#

but should i remove import discord import os or how?

cold sonnet
#

apparently you just have to click a stop button on thonny

#

and I assume he didn't miss that button

unreal siren
#

well

#

i stopped it

#

but it still didn't work i also tried running it in the console

ocean geyser
#

i tried top and under

#

and it doesnt work

cold sonnet
#

that's what I do, open cmd and type python3 Bot.py

unreal siren
#

yea i did that but it still does the same thing

lapis meadow
#

cannot import name 'app_commands' from 'discord' - I'm trying to do slash commands but this isn't working.

Google isn't being helpful ;-; Does anyone know how to fix

cold sonnet
lapis meadow
#

thx

unreal siren
#

Dani i also tried to search on google but i couldn't find anything there

ocean geyser
#

this is the error: typeerror init() missing 1 required keyword-only argument 'intents'

cold sonnet
unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

intents = Intents.default()
intents.members = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.

cold sonnet
#

maybe try restarting your raspberry

#

then there's no way the code is running twice

unreal siren
#

yea i already did that

ocean geyser
#

top or under?

#

ahh yes

unreal siren
#

I also tried putting the file into somewhere else but still the same stuff

ocean geyser
cold sonnet
cold sonnet
ocean geyser
wicked atlas
#

from the looks of it, they aren't using nextcord

unreal siren
#

is it possible i could send the file per dms because i can't send all of it in this channel

wicked atlas
#

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

cold sonnet
#

but you can encounter the error where you're requesting intents you haven't enabled

#

I'm calling it

#

you will

dull terrace
#

why are people STILL making bots that use message commands?

cold sonnet
#

message commands are classy

wicked atlas
#

plus they've been around a long time, so people who are coming into it new are getting all the old guides and stuff with message commands

cold sonnet
#

this only affects verified bots tho

ocean geyser
unreal siren
#

Dani can i send the bot file in your dms tho because i can't send the whole text in here

dull terrace
#

i guess if you're making a bot for a personal server it doesn't matter

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.

wicked atlas
unreal siren
#

oh

cold sonnet
#

or does it

wicked atlas
#

Whatever IP your replit is running on was probably blocked by cloudflare

cold sonnet
#

what does cloudflare have to do with this

wicked atlas
#

take a look in that html that's printed in the error

dull terrace
#

my brain will not focus right now

ocean geyser
unreal siren
#

ok so dani i just tried to run it on my windows pc and there it's working so it must be something internal on the raspi

cold sonnet
#

definitely

unreal siren
#

imma try reuploading the file onto the raspi

cerulean shale
dull terrace
#

what does 0.user do here

ocean geyser
cold sonnet
#

bot.user

wicked atlas
dull terrace
#

how is 0 bot though

cold sonnet
#

no idea

dull terrace
#

i thought formatting a string is replacing {}

wicked atlas
cold sonnet
#

it's a youtube tutorial thing to use this

ocean geyser
torn sail
unreal siren
#

i reuploaded the file and it's still the same i don't understand why tho

cerulean shale
dull terrace
cerulean shale
dull terrace
#

!e

print("this will print banana... {0}".format("banana", "apple"))
cold sonnet
#

can you like check the source code for the format method of str

cerulean shale
ocean geyser
wicked atlas
# ocean geyser i nothing understand

replits run on shared machines, which means that there are a bunch of people's replits out there with the same IP address. If a bunch of those are running discord bot's, some of them possibly even breaking or abusing ratelimits, cloudflare or discord might start blocking requests like you see in your replit

cerulean shale
cerulean shale
cerulean shale
ocean geyser
cerulean shale
dull terrace
cerulean shale
# ocean geyser

You gotta have 2 intents enabled, this isn't right, you gotta enable members intent and message_content intent

ocean geyser
#

but never used

cerulean shale
cold sonnet
#

the issue will be hosting right after

#

it was never where you edit the code

#

it's where you run it

cerulean shale
#

It's best to get a student vps and use it

#

!vps

cold sonnet
#

Imma go cuz

cerulean shale
#

Ight 💀

cerulean shale
unreal siren
#

Dani i also tried looking if there's another instance running but there is only one so now i'm even more confused

cerulean shale
wicked atlas
#

yeah thought so

primal token
#

thats why some bots get HTML response when ratelimited, iirc its just HTML body that says youre being ratelimited, cloudflare sends it

unreal siren
#

oh alr well my problem is that my bot sends the message of the old save and then the message of the new save so then i have 2 messages with a few changes i'm running the bot on a raspberry pi btw

cerulean shale
#

Oh-

potent spear
#

so when you stop the file from running, do you get any response from the bot when using a command?

cerulean shale
potent spear
unreal siren
#

just to point out i already tried restarting it

primal token
potent spear
#

you're not hosting it locally?

unreal siren
#

i am hosting it locally but there might be something still running it

potent spear
#

well, then there's your problem ofc

#

you know what to look for

#

what IDE are you using?

cerulean shale
unreal siren
cerulean shale
potent spear
#

so it's not like shitbot(1)

primal token
unreal siren
#

well when i wanna do a hotfix i do it on my pi and if i wanna add some new stuff i do it on my pc and SniperGlitcherz i don't have pycharm opened

cerulean shale
unreal siren
#

but i noticed the replit was on 💀

potent spear
#

and then just pull on your rpi

unreal siren
#

although i turned it off

potent spear
#

there's basically still some process running somewhere ofc, for you to find out

cerulean shale
primal token
#

?

cerulean shale
#

<!DOCTYPE html> or something iirc

unreal siren
cerulean shale
#

Don't even have my pc near me to check 💀

primal token
potent spear
cerulean shale
unreal siren
#

nah i mean to pull the github onto my pi and the process was replit it was still on for some reason

primal token
#

it still returns HTML, like when you e.g make a request to a url like https://youtube.com

potent spear
cerulean shale
potent spear
#

well, you should first of all put your project on a repo on github and learn basic git push commit and pull stuff

primal token
#

Why would replit ratelimit your traffic?

cerulean shale
#

Oh nvm then

#

✌️

slate swan
#
    async def lock_error(ctx, error):
        if isinstance(error, commands.MissingPermissions):
        em = discord.Embed(colour=discord.Color.orange(), description=f":warn: {ctx.author.mention}: You're **missing** permission: ``manage_channels``")
        await ctx.send(embed=em)```
#

can someone tell me why em is an error

#

its in a cog btw

cerulean shale
#

It's missing an indent

wicked atlas
#

everything that you want to be under that if statement should be indented

#

including the await ctx.send()

slate swan
#

wdym "indented"

wicked atlas
#

!indents

unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

slate swan
#

ohhh

#

its not an error no more

ocean geyser
wicked atlas
cerulean shale
ocean geyser
wicked atlas
#

With .env files, you'll need to use the python-dotenv package or something similar to load them

#

unless vsc has some kind of thing for that i'm not aware of

dull terrace
#

Hello! I'm brand new to making bots and I'm learning slash commands.

I was wondering how can I get the bot to get the guild ID so my friends can also use the bots in their discords.

This is why I have but I'm completely lost

cerulean shale
primal token
#

or something along the lines

slate swan
#
from discord.ext import commands

class Moderation(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self._last_member = None
    
    @commands.command()
    @commands.has_permissions(manage_channels = True)
    async def lock(self, ctx):
        await ctx.channel.set_permissiona(ctx.guild.default_role, send_messages = False)
        em = discord.Embed(colour = discord.Color.random(), description=f"{ctx.author.mention} is now locked")
        await ctx.send(embed=em)

    @lock.error
    async def lock_error(ctx, error):
        if isinstance(error, commands.MissingPermissions):
            em = discord.Embed(colour=discord.Color.orange(), description=f"![warn](https://cdn.discordapp.com/emojis/1009933102132514866.webp?size=128 "warn") {ctx.author.mention}: You're **missing** permission: ``manage_channels``")
            await ctx.send(embed=em)

    @commands.command()
    @commands.has_permissions(manage_channels = True)
    async def unlock(self, ctx):
        await ctx.channel.set_permissiona(ctx.guild.default_role, send_messages = True)
        em = discord.Embed(colour = discord.Color.random, description=f"{ctx.author.mention} is now unlocked")
        await ctx.send(embed=em)

    @unlock.error
    async def unlock_error(ctx, error):
        if isinstance(error, commands.MissingPermissions):
            em = discord.Embed(colour=discord.Color.orange(), description=f"![warn](https://cdn.discordapp.com/emojis/1009933102132514866.webp?size=128 "warn") {ctx.author.mention}: You're **missing** permission: ``manage_channels``")
            await ctx.send(embed=em)


    def setup(client):
        client.add_cog(Moderation(client))```
cerulean shale
# slate swan

Setup func should be out of your class and it should be async def and add_cog should be awaited

cerulean shale
slate swan
unreal siren
potent spear
#

basically version control, great for keeping track of shit

#

are you even connected / are you committing?

cerulean shale
potent spear
#

haven't seen any code, can't say

slate swan
cerulean shale
slate swan
# cerulean shale ```py class Moderation (commands.Cog): Your code.... async def setup(clien...
from discord.ext import commands

class Moderation (commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self._last_member = None

    @commands.command()
    @commands.has_permissions(manage_channels = True)
    async def lock(self, ctx):
        await ctx.channel.set_permissiona(ctx.guild.default_role, send_messages = False)
        em = discord.Embed(colour = discord.Color.random(), description=f"{ctx.author.mention} is now locked")
        await ctx.send(embed=em)

    @lock.error
    async def lock_error(ctx, error):
        if isinstance(error, commands.MissingPermissions):
            em = discord.Embed(colour=discord.Color.orange(), description=f"![warn](https://cdn.discordapp.com/emojis/1009933102132514866.webp?size=128 "warn") {ctx.author.mention}: You're **missing** permission: ``manage_channels``")
            await ctx.send(embed=em)

    @commands.command()
    @commands.has_permissions(manage_channels = True)
    async def unlock(self, ctx):
        await ctx.channel.set_permissiona(ctx.guild.default_role, send_messages = True)
        em = discord.Embed(colour = discord.Color.random, description=f"{ctx.author.mention} is now unlocked")
        await ctx.send(embed=em)

    @unlock.error
    async def unlock_error(ctx, error):
        if isinstance(error, commands.MissingPermissions):
            em = discord.Embed(colour=discord.Color.orange(), description=f"![warn](https://cdn.discordapp.com/emojis/1009933102132514866.webp?size=128 "warn") {ctx.author.mention}: You're **missing** permission: ``manage_channels``")
            await ctx.send(embed=em)

    def setup(client):
        client.add_cog(Moderation(client))```
#

same error in terminal

cerulean shale
#

I literally gave you the code and yet 🥲

#

This last part, the setup thing is called a function, it should be out of the class block as in remove the indents and add async before def and await before client.add_cog

slate swan
#
from discord.ext import commands

class Moderation (commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self._last_member = None

    @commands.command()
    @commands.has_permissions(manage_channels = True)
    async def lock(self, ctx):
        await ctx.channel.set_permissiona(ctx.guild.default_role, send_messages = False)
        em = discord.Embed(colour = discord.Color.random(), description=f"{ctx.author.mention} is now locked")
        await ctx.send(embed=em)

    @lock.error
    async def lock_error(ctx, error):
        if isinstance(error, commands.MissingPermissions):
            em = discord.Embed(colour=discord.Color.orange(), description=f"![warn](https://cdn.discordapp.com/emojis/1009933102132514866.webp?size=128 "warn") {ctx.author.mention}: You're **missing** permission: ``manage_channels``")
            await ctx.send(embed=em)

    @commands.command()
    @commands.has_permissions(manage_channels = True)
    async def unlock(self, ctx):
        await ctx.channel.set_permissiona(ctx.guild.default_role, send_messages = True)
        em = discord.Embed(colour = discord.Color.random, description=f"{ctx.author.mention} is now unlocked")
        await ctx.send(embed=em)

    @unlock.error
    async def unlock_error(ctx, error):
        if isinstance(error, commands.MissingPermissions):
            em = discord.Embed(colour=discord.Color.orange(), description=f"![warn](https://cdn.discordapp.com/emojis/1009933102132514866.webp?size=128 "warn") {ctx.author.mention}: You're **missing** permission: ``manage_channels``")
            await ctx.send(embed=em)

async def setup(client):
      await client.add_cog(Moderation (client))```
hushed galleon
# slate swan

that warning most likely means you're still using dpy 1.7.3 and not 2.0, since 1.7 expects setup to be a regular def function

cerulean shale
hushed galleon
#

sure

cerulean shale
#

💀

hushed galleon
#

py -m pip install -U discord.py, -U telling pip it should upgrade the package

dull terrace
#

So I have an issue and I'm not sure whats wrong. Does anyone know what this means?

Traceback (most recent call last):
  File "C:\Users\13129\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 851, in _do_call     
    return await self._callback(interaction, **params)  # type: ignore
  File "c:\Users\13129\Documents\slash-main\Slash.py", line 55, in ben
    await interaction.response.send_message(random.choice(ben))
  File "C:\Users\13129\AppData\Local\Programs\Python\Python310\lib\random.py", line 378, in choice
    return seq[self._randbelow(len(seq))]
TypeError: object of type 'Command' has no len()

Traceback (most recent call last):
  File "C:\Users\13129\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 1240, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Users\13129\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 876, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "C:\Users\13129\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 865, in _do_call     
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'ben' raised an exception: TypeError: object of type 'Command' has no len()```
slate swan
#
import discord
from discord.ext import commands
import os

from apikeys import *

intents = discord.Intents.default()
intents.members = True

client = commands.Bot(command_prefix=",", help_command=None, intents=intents)

@client.event
async def on_ready():
  print("vital is ready")
  print("--------------")
  await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="you.."))
  
from discord.gateway import DiscordWebSocket

class MyDiscordWebSocket(DiscordWebSocket):

    async def send_as_json(self, data):
        if data.get('op') == self.IDENTIFY:
            if data.get('d', {}).get('properties', {}).get('$browser') is not None:
                data['d']['properties']['$browser'] = 'Discord Android'
                data['d']['properties']['$device'] = 'Discord Android'
        await super().send_as_json(data)

DiscordWebSocket.from_client = MyDiscordWebSocket.from_client

initial_extentions = []

for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        initial_extentions.append("cogs." + filename[:-3])

if __name__ == '__main__':
    for extention in initial_extentions:
        client.load_extension(extention)
        
client.run(BOTTOKEN)``` Main.py btw
sick birch
#

why are you doing it this way?

slate swan
sick birch
#

This is like, messing with the internals

#

Are you just trying to set a custom browser and device metadata?

slate swan
#

?? I’m making a discord bot

sick birch
#
from discord.gateway import DiscordWebSocket

class MyDiscordWebSocket(DiscordWebSocket):

    async def send_as_json(self, data):
        if data.get('op') == self.IDENTIFY:
            if data.get('d', {}).get('properties', {}).get('$browser') is not None:
                data['d']['properties']['$browser'] = 'Discord Android'
                data['d']['properties']['$device'] = 'Discord Android'
        await super().send_as_json(data)

DiscordWebSocket.from_client = MyDiscordWebSocket.from_client

you can remove this entire part

#

Not sure why you're overriding internals to send custom metadata

slate swan
#

That’s just mobile status

#

I want mobile status tho lol

sick birch
#

Ah yeah that

slate swan
#

But sure

sick birch
#

Not sure if we can help with that as it might be bordering on rule 5

#

It's not documented usage, sort of a gray area

slate swan
#

Oh really I can just use normal status

sick birch
#

That would make things much much simpler

slate swan
#

Yea I’ll do that rn

sick birch
#

Not worth it just for "cosmetic" appearance

slate swan
#
from mimetypes import init
import discord
from discord.ext import commands
import os

from apikeys import *

intents = discord.Intents.default()
intents.members = True

client = commands.Bot(command_prefix=",", help_command=None, intents=intents)

@client.event
async def on_ready():
  print("vital is ready")
  print("--------------")
  await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="you.."))

initial_extentions = []

for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        initial_extentions.append("cogs." + filename[:-3])

if __name__ == '__main__':
    for extention in initial_extentions:
        client.load_extension(extention)
        
client.run(BOTTOKEN)```
#

is what i have now

sick birch
#

That's much better

#
for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        initial_extentions.append("cogs." + filename[:-3])

if __name__ == '__main__':
    for extention in initial_extentions:
        client.load_extension(extention)

can also be combined into one for loop

primal token
#

I wouldnt say that its a gray area tbh more like an unknow one, its not documented nor is their any rules about it nor does any apply to it exactly

#

so its not really something againts TOS or anything its just discord hasnt given much attention about it afaik

primal token
#

but i would agree its a bit hard to get it by editing internals and isnt really worth it (just make your own wrapper)

slate swan
#

what is this?

#
from discord.ext import commands

class Moderation (commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self._last_member = None

    @commands.command()
    @commands.has_permissions(manage_channels = True)
    async def lock(self, ctx):
        await ctx.channel.set_permissiona(ctx.guild.default_role, send_messages = False)
        em = discord.Embed(colour = discord.Color.random(), description=f"{ctx.author.mention} is now locked")
        await ctx.send(embed=em)

    @lock.error
    async def lock_error(ctx, error):
        if isinstance(error, commands.MissingPermissions):
            em = discord.Embed(colour=discord.Color.orange(), description=f"![warn](https://cdn.discordapp.com/emojis/1009933102132514866.webp?size=128 "warn") {ctx.author.mention}: You're **missing** permission: ``manage_channels``")
            await ctx.send(embed=em)

    @commands.command()
    @commands.has_permissions(manage_channels = True)
    async def unlock(self, ctx):
        await ctx.channel.set_permissiona(ctx.guild.default_role, send_messages = True)
        em = discord.Embed(colour = discord.Color.random, description=f"{ctx.author.mention} is now unlocked")
        await ctx.send(embed=em)

    @unlock.error
    async def unlock_error(ctx, error):
        if isinstance(error, commands.MissingPermissions):
            em = discord.Embed(colour=discord.Color.orange(), description=f"![warn](https://cdn.discordapp.com/emojis/1009933102132514866.webp?size=128 "warn") {ctx.author.mention}: You're **missing** permission: ``manage_channels``")
            await ctx.send(embed=em)

async def setup(client):
      await client.add_cog(Moderation (client))``` Idk why my commands wont work
sick birch
sick birch
slate swan
sick birch
#

Can I see them?

slate swan
#

Wdym on dev page?

sick birch
#

!intents The discord developer page

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

intents = Intents.default()
intents.members = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.

sick birch
#

Yeah you don't have message content intent enabled

slate swan
sick birch
#

intents.message_content = True in your code to enable it

slate swan
#

why are those errors??

sick birch
#

if you hover over them they'll tell you what's wrong

#

you should always fix those errors

slate swan
#

is says Intents is not defined by pylance

sick birch
#

Yes because it doesn't know what Intents is

#

You have to tell it what it is

#

You can either import it from the discord module (not recommended due to namespace pollution)
or you can use discord.Intents.default() (recommended)

#

And setting the message content flag to true after you've passed it into the bot is the same as not passing it in at all

sick birch
#

Well now you're not saving discord.Intents.default() anywhere

#

it just makes the object and throws it away

slate swan
#

why does it do that bru

sick birch
silk fulcrum
#

Hi, Robin u still here? I woke up just now

sick birch
#

You're telling python, "hey, make this object, but just throw it away once you're done. don't worry about it." then later, you're asking it "remember the object that you threw out? can you get it for me" and python can't, it's in the trashcan

sick birch
silk fulcrum
sick birch
#

not much, i'm about to head off to bed lol

silk fulcrum
#

oh lol

primal token
limber bison
#

I dont no why but in one channel of my server , search thing not working, like it show 3-4 days back searches

#

How can I fix it

sick birch
sick birch
maiden fable
sick birch
#

I'd love to, but honestly GH workflows are out of my expertise and i kinda feel like hitting the hay rn lmao

maiden fable
#

Oh haha all cool. Have a good one!

primal token
crimson frigate
maiden fable
#

Isn't iP still in like 3.4 or smth?

crimson frigate
raven bolt
#

uwu

maiden fable
#

Tbh no one has really tried, but you should give it a try!

raven bolt
#

just, don't hassle if you speak c++

crimson frigate
crimson frigate
crimson frigate
raven bolt
#

there's a library for everything by now

maiden fable
#

@crimson frigate highly unlikely it will work. Because iP targets Python 3.6

raven bolt
unkempt canyonBOT
#

A pure Python girlfriend she can help you build operation scripts, send data report, monitor the system and do a lot of things you undreamed!The most important, her heart(core lib) is all completely free!

raven bolt
#

wth is that

crimson frigate
#

girlfriend haha

glacial sail
#

it's NSFW, and not appropriate here

maiden fable
#

Sorry!

silk fulcrum
#

I think there is also a boyfriend

#

there actually is... bruv

raven bolt
#

what if you put girlfriend and boyfriend in the same env

slate swan
#

OSError

silk fulcrum
#

😳

#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

torn sail
#

Discum is a self bot lib

silk fulcrum
#

still breaks ToS

torn sail
#

!pypi discum

unkempt canyonBOT
#

A Discord API Wrapper for Userbots/Selfbots written in Python.

silk fulcrum
#

you are still braking ToS

strong remnant
#

'laws' 🤓

silk fulcrum
torn sail
primal token
tropic burrow
#
@client.command()
async def hangman(ctx):
  r = RandomWords()
  word = r.get_random_word(hasDictionaryDef="true")
  length = len(word)
  data = dictionarysearch(word)
  print(data[0])
  for char in word:
    word.replace(char,'_')
 
  
  mbed = discord.Embed(
    title=f"Length of Word: {length} Reply to guess",
    description = f"{word}"
  )

  await ctx.channel.send(embed=mbed)
  ``` literally nothing happens. also the word is generated, i just want to replace all the letters of the word with underscore and then display
silk fulcrum
tropic burrow
#

yes

#

nothing happens

#

i see nothing in console

silk fulcrum
#

by the way, you can use ctx.send

tropic burrow
#

ik

silk fulcrum
#

what is RandomWords

tropic burrow
#

generate a random word

#

for hangman

silk fulcrum
#

is that a library?

tropic burrow
#

!pypi Random-Word

unkempt canyonBOT
tropic burrow
#

yes

grim oar
#

faker is better bro

tropic burrow
#

what is faker

silk fulcrum
#

!pip faker

unkempt canyonBOT
#

Faker is a Python package that generates fake data for you.

grim oar
#

!pypi faker

unkempt canyonBOT
#

Faker is a Python package that generates fake data for you.

tropic burrow
#

how do i get random word i can see names and adreses

grim oar
#

Idk man try finding

silk fulcrum
grim oar
#

Brah let me find

tropic burrow
tropic burrow
#

using api

shrewd apex
#

use pydictionary

tropic burrow
shrewd apex
#

!pypi pydictionary

unkempt canyonBOT
tropic burrow
#

OH

#

ok

silk fulcrum
grim oar
#

h

tropic burrow
#

i just want to resolve my problem, it works when i dont add the for loop

#

but when i do it does not work

#

i need it to replace the chars with "_"

silk fulcrum
tropic burrow
#

ok

shrewd apex
#

imagine using for loop 😔

silk fulcrum
shrewd apex
#

for _ in range

#

python semantics

silk fulcrum
#

lol

tropic burrow
#

nothing happened

#
under = "_"*length
 
  
  mbed = discord.Embed(
    title=f"Length of Word: {length} Reply to guess",
    description = f"{under}"
  )

  await ctx.channel.send(embed=mbed)
silk fulcrum
#

indentation?

tropic burrow
#

also this is replit

silk fulcrum
#

replit 😭

grim oar
#

did you restart

tropic burrow
#

restart what

grim oar
#

The program

silk fulcrum
#

bot

#

or reload extension

#

well this doesnt look like a cog

#

and use await ctx.send

grim oar
#

Isnt a cog bro

shrewd apex
#

send the whole command code

devout nebula
#

Hi! I have an event that doesn't work and idk why

@bot.event
async def on_message(message):
    channel = bot.get_channel(997568539223396502)
    salts = bot.get_user(480341304799395840)
    await salts.send(f"{message.author.name} >> {message.content}")
    await bot.process_commands(message)```
slate swan
devout nebula
#

Yes

slate swan
#

that's why

devout nebula
#

But i added a await bot.process_commands(message) so it should work?

slate swan
#

make them a listen

devout nebula
#

Thats the only option?

#

Its kinda alot of code

slate swan
#

!d discord.ext.commands.Bot.listen

unkempt canyonBOT
#

@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready")

The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").

Example...
slate swan
#

it's 2 lines you have to change

devout nebula
#

Oh

slate swan
devout nebula
#

@listen(name=on_message)?

torn sail
#

@bot.event -> @bot.listen()

devout nebula
#

Thanks

#
Community songs server >> Saltss_ >> T
Community songs server >> Community songs server >> Saltss_ >> T
Community songs server >> Community songs server >> Community songs server >> Saltss_ >> T
Community songs server >> Community songs server >> Community songs server >> Community songs server >> Saltss_ >> T
Community songs server >> Community songs server >> Community songs server >> Community songs server >> Community songs server >> Saltss_ >> T
Community songs server >> Community songs server >> Community songs server >> Community songs server >> Community songs server >> Community songs server >> Saltss_ >> T
Community songs server >> Community songs server >> Community songs server >> Community songs server >> Community songs server >> Community songs server >> Community songs server >> Saltss_ >> T
Community songs server >> Community songs server >> Community songs server >> Community songs server >> Community songs server >> Community songs server >> Community songs server >> Community songs server >> Saltss_ >> T
Community songs server >> Community songs server >> Community songs server >> Community songs server >> Community songs server >> Community songs server >> Community songs server >> Community songs server >> Community songs server >> Saltss_ >> T``` holy shit
#

It keeps repeating this

shrewd apex
#

if it's all in same file just put them under one on_message 💀

slate swan
#

what other shit do u have

shrewd apex
#

it's probably responding to its own message

slate swan
#

yeah

devout nebula
#

Yeah but it sends in dms

#

Not the server

shrewd apex
#

u have to add a check if message.author.bot: return and if message.guild is None: return

slate swan
#

so it doesn't reply to itself ^

devout nebula
#

Thanks

#

But it sends in dm so it doesnt matter

slate swan
#

on message doesn't just look in servers

tropic burrow
shrewd apex
#

how u wanna space it

#

u can just do "_ "*len(word)

#

add space at end

tropic burrow
#

ok

#

like this?

#

@shrewd apex

#

this is whats happening when i do that

#

literally nothing comes in the description of the embed

shrewd apex
#

u have to set it in u desc

#

ur*

tropic burrow
#

i did

#

i did a f string

shrewd apex
#

show

tropic burrow
#

actually screw this ima change it to dashes coz it works

light jungle
#

Hello everyone, I have a question, how can I request a picture from a person when he enters a command? (The essence of the bot is a person enters a command and throws his picture, after that the bot sets up another one on this picture) The modules that will be used are
discord py (nextcord maybe)
and pillow

#

I was already told what argument to write something that asked for a picture, but to be honest, I did not understand how to apply it, the distortion in the documentation did not find anything

slate swan
#

I am trying to add a role to a user when a specific message is reacted to. I tried to do something like this but it is not working for me.

@client.event
async def on_raw_reaction_add(payload):
    ourMessageID = 1014040026444730388
    
    if ourMessageID == payload.message_id:
        emoji = payload.emoji.name
        if emoji == ('✅'):
            role = discord.utils.get(guild_id.roles, name="Shawnland")
        elif emoji == ('👎'):
            role = discord.utils.get(guild_id.roles, name = 'Verification')
        await member.add_roles(role)
cloud dawn
#

Message object has an attachment attribute that returns a list in any library that is the same.

light jungle
#

To be honest, I don’t quite know what this argument is and how to use it.

#

like, I would just like to know the argument that allows you to upload a picture

cloud dawn
cloud dawn
#

You would need to run pillow in an async executor inside that edit said image then return the result.

slate swan
# cloud dawn Does it pass the first if? Could you check?

yes when I add this it goes through, so my issue is assigning the role. when I type await member.add_roles(<roleid>) it has a line underneath the members. Also doesnt work with user. Im assuming its because payload

if emoji == ('✅'):
            print("HellO")
light jungle
cloud dawn
#

Pretty sure payload has a member attribute but you don't have that yet.

#

Thus payload.member

cloud dawn
shrewd apex
#
@commands.command()
async def img(CTX: commands.Context, image: discord.Attachment):
    ...
#

image here is ur attachment

cloud dawn
shrewd apex
#

there is now

cloud dawn
#

lmao

shrewd apex
#

i used it in my hybrid commands

cloud dawn
#

What lib?

shrewd apex
#

discord

#

!d discord.Attachment

unkempt canyonBOT
#

class discord.Attachment```
Represents an attachment from Discord.

str(x) Returns the URL of the attachment.

x == y Checks if the attachment is equal to another attachment.

x != y Checks if the attachment is not equal to another attachment.

hash(x) Returns the hash of the attachment.

Changed in version 1.7: Attachment can now be casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") and is hashable.
cloud dawn
slate swan
cloud dawn
shrewd apex
#

list of discord role objects or just a single role object will also do

cloud dawn
#

They also need to be role objects or snowflakes.

#

await payload.member.add_roles(discord.Object(<role id>))

#

In this case Object will just create a snowflake here since they only need the ID to assign the role.

slate swan
#

Thank you ❤️

tropic burrow
#

so pydictionary isnt working on replit for some reason, so i have to use an dictionary api. why does this not work

def dictionarysearch(word):
  api = "https://api.dictionaryapi.dev/api/v2/entries/en/"+word
  r = requests.get(api)
  json_data = r.json()
  return json_data

 @client.command()
async def hangman(ctx):
  r = RandomWords()
  word = r.get_random_word(hasDictionaryDef="true")
  length = len(word)
  data = dictionarysearch(word)
  print(data[0]["meanings"])
  under = "-"*length
 
  
  mbed = discord.Embed(
    title=f"Length of Word: {length} Reply to guess",
    description=f"{under}"
  )

  await ctx.channel.send(embed=mbed)
high tapir
#

guys could anyone advise me
how to write an error handling if someone put text value !solana?
because i wrote simple function which converts solana to my local currency which is pln

import discord
from discord.ext import commands
intents = discord.Intents(messages=True, guilds=True, message_content = True)
bot = commands.Bot(command_prefix='!', intents=intents)

@bot.command()
async def solana(ctx, arg:float):
    result = round(arg * float(pricesol) * float(pricezl))
    await ctx.send('Your {x} solas are worth {result}zł'.format(result=result, x=arg))

bot.run("token")

i have code which scrap values of sol and usdt above ^^

#

but im wondering how i could write error handling if someone will something like !solana kekw, because basically this type hint arg:float change every type of data to the float

shrewd apex
#

!d discord.ext.commands.BadArgument

unkempt canyonBOT
#

exception discord.ext.commands.BadArgument(message=None, *args)```
Exception raised when a parsing or conversion failure is encountered on an argument to pass into a command.

This inherits from [`UserInputError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.UserInputError "discord.ext.commands.UserInputError")
shrewd apex
#

raise this and catch it in the error handler

tropic burrow
light jungle
#

Is it possible to insert an image in discord modals?

slate swan
#

not for now

#

Cogs are a discord.py feature that allows you to divide your commands into seperate categories constructed using classes.
you can have cogs in different files rather than a single bot file

#

!d discord.ext.commands.Cog here's how you use them

unkempt canyonBOT
#

class discord.ext.commands.Cog(*args, **kwargs)```
The base class that all cogs must inherit from.

A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the [Cogs](https://discordpy.readthedocs.io/en/latest/ext/commands/cogs.html#ext-commands-cogs) page.

When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta") are equally valid here.
shrewd apex
#

yes kinda its like handy plug-in

slate swan
#

yesnt, discord.py just imports a setup function from the module

unkempt canyonBOT
#

discord/ext/commands/bot.py lines 939 to 943

try:
    setup = getattr(lib, 'setup')
except AttributeError:
    del sys.modules[key]
    raise errors.NoEntryPointError(key)```
winged oriole
#

i'm hosting my discord bot on windows, but i want to host it on linux. but this code is not working. can anyone help me?

token = json.load(open('data\\config.json'))['token']` #code that dont work on linux```

whole bot code

import discord
from discord.utils import get
from discord.ext import commands, tasks
from discord import Intents
import discord.ext
import discord.ext.commands
from discord.ext.commands import has_permissions, MissingPermissions
import aiohttp
import sys
from datetime import datetime
import sqlite3
import requests
import random
import json
import time
import os

prefix = json.load(open('data\config.json'))['prefix']
token = json.load(open('data\config.json'))['token']

all bot command here

if name == "main":
client.run(token)

rugged shadow
#

replace \\ with /

winged oriole
#

ok

#

it worked, thanks

rugged shadow
#

np

tawdry tendon
#

Wdym by you get your own unique answer

slate swan
tawdry tendon
#

I can’t understand what your trying to say

#

Do it as an example

slate swan
#

example. When you click on the Основные option, the bot writes 123 to you. When you click on the Модерация option, the bot writes 765.

#

@tawdry tendon

tawdry tendon
#

Ahhh

slate swan
# tawdry tendon Ahhh

пример. При нажатие на вариант Основные бот тебе пишет 123. При нажатии на вариант Модерация бот пишет 765.

tawdry tendon
#

I don’t understand that but ok

slate swan
#

do you even know what a select menu is!?

tawdry tendon
#

Anyways, I did this with a dropdown it’s probably similar, so give the button a value and if that value is clicked then send something

tawdry tendon
slate swan
tawdry tendon
#

discord.SelectOption(label="Math Command", description="View math commands", value="value1")

#

Can you send me backsticks

#

I’m on mobile rn

#

@slate swan

#

?????

#

!code

slate swan
#

how to make the bot respond to you when you click on the list item. But so that the answer is not the same, but with different options !?

tawdry tendon
#

???

#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

slate swan
#

the list that is select menu!!!!

tawdry tendon
#

Ok

slate swan
#

the select menu list is displayed. You click on one option you get a message

tawdry tendon
#

discord.SelectOption(label="Math Command", description="View math commands", value="value1") ```
#

That’s the option

#

And for it to respond , I gave it the value “1”

#

Or you can use the label but just use value for this

#

And this is to respond

#

async def select_callback(self, interaction, select):
        if select.values[0] == "value1":
            await interaction.response.send_message(embed=mathembed)

#

And in the send_message you can type whatever you want or make an embed

#

Do you understand now

slate swan
tawdry tendon
#

Yes

#

Add a different value to each option and send whatever you want in it

#

What’s the error

#

Can you send ONLY the part where the error is

#

I don’t mean like that

#

Like show the code where the error is

slate swan
#

if select.values[2] == "value3":

shrewd apex
tawdry tendon
#

if select.values[0]

tawdry tendon
shrewd apex
#

it wont work coz u need the class object

tawdry tendon
#

It does work

shrewd apex
#

here its either self or Dropdown

#

the class name

#

select is not even defined here

tawdry tendon
#
async def select_callback(self, interaction, select):
     if select.values[0] == "value1":
         await interaction.response.send_message(embed=mathembed)```
#

like that it will work

shrewd apex
#

callback has no positional arg select

slate swan
#

@shrewd apexhow to make a message appear when clicking on the options in the list. The message should not be the same. And the different options

shrewd apex
#

so what u sent won't work

shrewd apex
tropic burrow
#

how do i like make a system to check for replies for the message the bot set

shrewd apex
#

wdym how by code in the callback...🗿

#

use the callback

tropic burrow
# tropic burrow how do i like make a system to check for replies for the message the bot set

for example

@client.command()
async def hangman(ctx):
  r = RandomWords()
  word = r.get_random_word(hasDictionaryDef="true")
  length = len(word)
  data = dictionarysearch(word)
  print(word)
  meaning = data[0]["meanings"][0]["definitions"][0]["definition"]
  under = "-"*length
 
  
  mbed = discord.Embed(
    title=f"Length of Word: {length} Reply to guess",
    description=f"{under}"
  )

  sentmsg = await ctx.channel.send(embed=mbed)

there has to be some message to check for replies for sentmsg

slate swan
#

@tropic burrow dude. It's useless to ask something here, I've probably been asking the same thing for 5 hours and they can't answer me how to do it all the time they say what I've already done!!!

slate swan
unkempt canyonBOT
#

wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
meager chasm
#

You can wait for an on_message event and in the check see if the message.reference is same as sentmsg

tropic burrow
#

wait

toxic thicket
#
intents = Intents.default()
intents.members = True
bot=commands.Bot(command_prefix = ".", intents = discord.Intents.all()) 

discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead. 

The site also includes all intents, what's the problem?

tropic burrow
meager chasm
#

Message content, presences and members

slate swan
#

@tawdry tendondon't reply to my messages anymore. You're writing what I've already done. If you don't understand what I want to do, don't get in the way

shrewd apex
#

u tell me how many callbacks do u think a selectmenu can have?

slate swan
pliant gulch
shrewd apex
#

its simple python do i have to write the code down and spoon feed u u just need to have a if statement and check which option was pressed with custom id and customise ur message

shrewd apex
meager chasm
tropic burrow
# unkempt canyon

@meager chasm the example i saw in the read the docs is only for a ON message thing. How do i make for a command

meager chasm
#

And call wait_for in the command

pliant gulch
# toxic thicket Yes

Please make sure you're using the right bot token (the one that has the intents enabled on the developer site) That'll be the only other reason why it's producing an error like the one you are experiencing

tropic burrow
meager chasm
#

Why would u do that

shrewd apex
#

nope

slate swan
loud junco
#

why not use @bot.command

shrewd apex
#

coz he defined client = bot yt i think

loud junco
#

lmao

tropic burrow
loud junco
#

💀

shrewd apex
meager chasm
#

that is allow in python

slate swan
#

@shrewd apex how to make several options for the message that the select menu can give when clicking on the items in the list!?

tropic burrow
#

what is the check parameter for

#

in wait_for

toxic thicket
#

Now the bot works, but gives an error, the token has changed, but still gives...

discord.client: logging in using static token
 discord.gateway: Shard ID None has connected to Gateway (Session ID: 77650add909b1a30d04d6595abb600a8). 
meager chasm
#

See example in docs

pliant gulch
light jungle
shrewd apex
tropic burrow
light jungle
#

By the way, about the static token, I don’t have such an error in the nextcord library when I do something with classes, but in discord.py there is

pliant gulch
#

It isn't an error

#

It's a debug log

meager chasm
#

Oh u mean does it return bool

light jungle
slate swan
# shrewd apex u can just use the value param for options and get the value from interaction.da...
class Dropdown(discord.ui.Select):
    def __init__(self):

        # Set the options that will be presented inside the dropdown
        options = [
            discord.SelectOption(label = "Основные", emoji= ":large_blue_diamond:", description= "Основные команды сервера", value="value1"),
            discord.SelectOption(label = "Модерация", emoji= ":large_blue_diamond:", description= "Команды для модерирования сервера", value="value2"),
            discord.SelectOption(label = "Взаимодействие", emoji= ":large_blue_diamond:", description= "Команды взаимодействия между участниками", value="value3"),
            discord.SelectOption(label = "Экономика", emoji= ":large_blue_diamond:", description= "Команды связаные с экономикой", value="value4"),
            discord.SelectOption(label = "Настройки", emoji= ":large_blue_diamond:", description= "Команды настройки", value="value5")
        ]

        super().__init__(placeholder='Список команд сервера', min_values=0, max_values=5, options=options)
    async def callback(self, interaction: discord.Interaction):
        if self.values[0] == "value1":
            await interaction.response.send_message(
                embed = discord.Embed(description= f'{self.values[0]}', colour=0xF1C40F),
                delete_after=60
            )
        if self.values[0] == "value2":
            await interaction.response.send_message(
                embed = discord.Embed(description= f' {self.values[1]}', colour=0xF1C40F),
                delete_after=60
            )
        if self.values[0] == "value3":
            await interaction.response.send_message(
                embed = discord.Embed(description= f' {self.values[2]}', colour=0xF1C40F),
                delete_after=60
            )

does not work

meager chasm
#

Yes it does

pliant gulch
light jungle
meager chasm
#

U can change discord py default logging if u don't like it

slate swan
shrewd apex
#

!d discord.SelectOption

unkempt canyonBOT
#

class discord.SelectOption(*, label, value=..., description=None, emoji=None, default=False)```
Represents a select menu’s option.

These can be created by users.

New in version 2.0.
shrewd apex
#

use the value kwarg bruh

#

u are not even trying to understand

#

u are just crying its not working from past 15 mins

slate swan
unkempt canyonBOT
#

4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.

slate swan
#

@shrewd apexand how the fuck to understand it!?

shrewd apex
#

in the callback once do print(interaction.data)

#

u have to parse it from the dict

meager chasm
shrewd apex
limber bison
#

i dont know why , search not working in some channels

#

what should i do ?

shrewd apex
#

what search

tawdry tendon
#

its literally different smh

slate swan
tropic burrow
shrewd apex
#

yes so now u know how to parse ur values?

#

now u know which option was pressed use this info

tropic burrow
#

this is word

word = r.get_random_word(hasDictionaryDef="true")
shrewd apex
#

m.author == ctx.author?

#

or is it ffa hangman

tropic burrow
#

yeah ffa

shrewd apex
#

ic

tropic burrow
#

i just have to check the channel

#

is the same

slate swan
tropic burrow
#

i have to send something if they are wrong

#

so i will remove the m.content in word

slate swan
shrewd apex
meager chasm
placid skiff
placid skiff
shrewd apex
#

it doesn't

slate swan
meager chasm
shrewd apex
#

but actually u can just use a try except for this

#
x = wait_for()
try:
    ...
except asyncio.TimeoutError:
    ...
else:
    ...
tropic burrow
#

will this work

meager chasm
#

What

tropic burrow
#
def check(m):
   if m not in word:
     await ctx.send("Wrong!")
   else:
        return ctx.channel == m.channel
    
  msg = await client.wait_for('message',check=check)
#

wait i should return something

meager chasm
tropic burrow
#

if m is not in wor

placid skiff
#

wait_for raises a Timeout, so the while will loop until the timeout is reached

meager chasm
#

U can set timeout to None

tropic burrow
unkempt canyonBOT
#

4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.

meager chasm
#

I don't think check can be async

shrewd apex
#

is ur iq negative

meager chasm
hollow badger
#

@shrewd apex Please respect other members.

shrewd apex
#

...

meager chasm
#

not Asher bruh!!

#

The exlin guy being very very salty !!

tropic burrow
#

check cant be async?

hollow badger
#

I'm sorry, but he was being rude right before a Mod ping. 😉

shrewd apex
#

🥲

#

yes sir my bad

meager chasm
tropic burrow
#

do i have to put like a return false?

#

after it not there

shrewd apex
#

yes it checks for a boolean value

#

normally i just use a lambda

tropic burrow
#
if m not in word:
     await ctx.send("Wrong!")
     return False
   else:
        return ctx.channel == m.channel
    ```
slate swan
tropic burrow
#

what happens if it is false?

shrewd apex
#

nothing its passed

placid skiff
#

nothing, it will wait for the next event that you're handling

meager chasm
tropic burrow
#

so after the ctx.send nothing happens

shrewd apex
#

it doesn't meet the requirements so its equivalent to jus a pass statement

#

yes

meager chasm
#

ofc that is sudo code

#

u need await that stufds

lilac spear
#

Guys, is @task.loop() working for your bots?

hollow badger
meager chasm
shrewd apex
tropic burrow
shrewd apex
#

otherwise it will just run on

meager chasm
#

break will exit while loop and go to next code

hollow badger
#

If there is ever a concern you can ping Mods or open a thread with the ModMail bot by DMing it.

slate swan
shrewd apex
#

yeah but if he keeps answering wrong the while loop wont end

#

there is no check for timeout either

placid skiff
meager chasm
lilac spear
# meager chasm Yees

I triend using the API reference for discord.ext.tasks, and it doesn't work, here's the code


class MyCog(commands.Cog):
  def __init__(self):
      self.index = 0
      self.printer.start()

  def cog_unload(self):
      self.printer.cancel()

  @tasks.loop(seconds=5.0)
  async def printer(self):
      print(self.index)
      self.index += 1

bot = MyCog()
primal token
meager chasm
#

And he can change it if he wants

hollow badger
shrewd apex
#

well indeed

meager chasm
tropic burrow
#

so do i have put a guessing

#

parameter

placid skiff
meager chasm
meager chasm
placid skiff
meager chasm
#

It only blocks the task so it doesn't matter

placid skiff
#

so let's make an example you do 9 fails and then print the correct answer

#

you will read 10 times the correct message

meager chasm
#

What!! No

placid skiff
#

cuz all that wait_for will be dispatched when the check is passed

shrewd apex
#

actually let him just try it he can change it later to what i sent before according to his wishes

meager chasm
#

no wtf

tropic burrow
meager chasm
#

It not calling 10 wait_for

tropic burrow
#

and say like the guy was hanged

meager chasm
#

If first wait_for is satisfied

#

Because there is break in the loop

placid skiff
meager chasm
#

loops while condition is True

shrewd apex
#

it will be firing a wait_for after every attempt

tropic burrow
placid skiff
#

it doesn't mean anything, the wait_for waits for an event, it does not metter where you call it

tropic burrow
#

parameter

placid skiff
#

an event will be always dispatched

meager chasm
shrewd apex
dusk glade
#

how to make discord bots

#

what package is the best

#

what is the best api

tropic burrow
#

wait

shrewd apex
#

well actually endysis is not wrong this setup can be used if u want to limit the number of guesses or set the number of guesses

tropic burrow
#

also @meager chasm why would i break it if the guess is right?

#

because i have to continue the guess game

#

shouldn't i use put a check and then use continue if not all letters have been guesses

glad cradle