#discord-bots

1 messages · Page 1010 of 1

slate swan
#

like that?

#

yes exactly! but you would also need member Intents, in case you don't know what is it, use !intents command here

#

!intents

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 the Members and Presences intents, which are needed for events such as on_member 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.

slate swan
#

can anyone help me make a command to find people by putting their name? For example: .find (name) and it finds all people with that name or similar name

terse bane
#

lol

oak oar
slate swan
cloud dawn
#

Define "find people"

slate swan
#

not "similar" but same name works

#

!pip fuzzywuzzy iterate thru bot.users and use this, to compare similar names

unkempt canyonBOT
sacred gull
#

yes

slate swan
#

Sorry for my bad English. I'm Portuguese and I'm not fluent in English.
I'll give you a context for you to understand what I want to do:
Today there was a raid on a server that I am an administrator and I wanted to make a command that would banish all members who had a specific name.

For example: antiraid (name). And all members who had the name (name), would be banned.

sick birch
sacred gull
slate swan
sick birch
sick birch
sacred gull
sick birch
#

also, you only really need to migrate if you're going from text commands to slash commands

sacred gull
#

The whole async/await stuff

sick birch
#

Is that what you're doing?

sacred gull
#

No, I'm trying to make it so I can get my cogs to load

sick birch
#

Cogs should be same from 1.7.3 to 2.0

cloud dawn
#

Best would be to just tempban all users who recently joined.

sacred gull
#

Not the mail file

sacred gull
sick birch
sick birch
sacred gull
#

I know I need to put it in a class with some other stuff, but that's the part that I can't figure out correctly

#

And I've been trying for over 2 hours or something now

#

and I still can't figure it out

sinful wind
#

Is there any way (using discord.py) to check if someone has connected their steam account and fetch their friend code?

sick birch
#
class MyBotSubclass(commands.Bot):
  ...
  async def setup_hook():
    await load_extension(...)
    # setup stuff here
sick birch
sacred gull
sinful wind
sacred gull
#

But this is what I can't figure out because I have alot more code in my main file that needs to be done

sick birch
sinful wind
#

Can I get their profile name?

#

Surely that's public?

cloud dawn
sacred gull
sick birch
sick birch
#

For profile information

sinful wind
#

I guess alternatively I can prompt the user to insert their friend code in Discord in some sort of command

sick birch
#

Deprecated from 1.7 it seems

cloud dawn
sacred gull
sick birch
sacred gull
#

here i'll send my main file

#

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

sacred gull
#

I can probably get rid of the database stuff because I can put it in my event cog

sick birch
#

Why are you manually doing the websocket stuff

sacred gull
cloud dawn
feral lichen
#

i have no clue if this is possible in python in general, but how would one add to an int without making a new variable? ```py
a = int(0)

@bot.event
async def on_guild_channel_delete(ct):
a + int(5)
print(a)

cloud dawn
#

Which is against ToS i might add.

sick birch
#

Not sure how well subclassing is going to work with a manual websocket connection

sacred gull
sick birch
sacred gull
#

Oh didn't know

#

My bad, i'll remove it after I fixed this

sick birch
#

You have to subclass commands.Bot, not DiscordWebSocket

sacred gull
sick birch
#

What do you mean where would you leave it?

sacred gull
#
class MyBotSubclass(commands.Bot):
  ...
  async def setup_hook():
    await load_extension(...)
    # setup stuff here

bot = MyBotSubclass
bot.run(bot.config_token)
#

Because this is what I would do, right?

unkempt canyonBOT
#

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

sacred gull
#

Ok but what goes where then

#

That's what I'm also confused about

cloud dawn
supple thorn
#

!e ```py
a = 34
a += 35
print(a)

unkempt canyonBOT
#

@supple thorn :white_check_mark: Your eval job has completed with return code 0.

69
supple thorn
#

like this?

cloud dawn
#

Python is a dynamically typed language.

feral lichen
#

but ill see

feral lichen
slate swan
feral lichen
#

oh i didnt see that lol

supple thorn
feral lichen
#

doesnt work like that but ill just do the thing and see if it works lmfao

sick birch
slate swan
#

!e ```py
class Bot():
...

bot = Bot()
bot.number = 1

def a():
bot.number+=2

a()
print(bot.number)
#clearly works

unkempt canyonBOT
#

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

3
feral lichen
#

thanks

sacred gull
#

main file:

import json  # for json
import logging  # for logging
from pathlib import Path  # for paths
import discord  # for discord
import sqlite3
from utils.data import Bot

cwd = Path(__file__).parents[0]
cwd = str(cwd)
print(f'{cwd}\n-----')
print(discord.__version__)


async def getprefix(bot, ctx):
    db = sqlite3.connect('cupid.db')
    cursor = db.cursor()
    cursor.execute('SELECT prefix FROM prefixes WHERE guild_id = ?', (ctx.guild.id,))
    data = cursor.fetchone()
    if data:
        prefix = str(data[0])
    if not data:
        prefix = ','
    db.commit()
    cursor.close()
    db.close()
    return prefix

bot = Bot(
    intents=discord.Intents.all(),
    command_prefix=getprefix,
    case_insensitive=True,
    owner_id=742623359409586227,
    activity=discord.Game(name=",help")
)


config_file = json.load(open(cwd + '/config/config.json'))
bot.config_token = config_file['token']
logging.basicConfig(level=logging.INFO)
bot.version = 'v0.1.3'


bot.run(bot.config_token, reconnect=True)

utils.data file:

import os
from discord.ext.commands import AutoShardedBot
from pathlib import Path

cwd = Path(__file__).parents[0]
cwd = str(cwd)


class Bot(AutoShardedBot):
    def __init__(self, *args, prefix=None, **kwargs):
        super().__init__(*args, **kwargs)
        self.prefix = prefix

    async def setup_hook(self):
        if __name__ == '__main__':
            for file in os.listdir(cwd + '/cogs'):
                if file.endswith('.py') and not file.startswith('_'):
                    await self.load_extension(f'cogs.{file[:-3]}')

sacred gull
sick birch
#

hmmm

sacred gull
#
class woke(commands.Cog):

    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_ready(self):
        print(f"{self.__class__.__name__} cog has been loaded\n-----")
sacred gull
sick birch
#

You're making multiple websocket connections to the gateway

#

get rid of your manual connection

sacred gull
#

I deleted the websocket stuff

sick birch
#
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
``` this stuff?
#

can you post an updated main file

sacred gull
#

that's this

#

Those are the 2 most recent updated files

sick birch
#

get rid of the if name main part

#

you don't need that inside the setup hook

sacred gull
#

ok

#
INFO:discord.client:logging in using static token
Traceback (most recent call last):
  File "C:\Users\ego\Documents\Development\Discord\murder\cupid.py", line 46, in <module>
    bot.run(bot.config_token, reconnect=True)
  File "C:\Users\ego\anaconda3\lib\site-packages\discord\client.py", line 711, in run
    asyncio.run(runner())
  File "C:\Users\ego\anaconda3\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Users\ego\anaconda3\lib\asyncio\base_events.py", line 642, in run_until_complete
    return future.result()
  File "C:\Users\ego\anaconda3\lib\site-packages\discord\client.py", line 708, in runner
    await self.start(*args, **kwargs)
  File "C:\Users\ego\anaconda3\lib\site-packages\discord\client.py", line 681, in start
    await self.login(token)
  File "C:\Users\ego\anaconda3\lib\site-packages\discord\client.py", line 544, in login
    await self.setup_hook()
  File "C:\Users\ego\Documents\Development\Discord\murder\utils\data.py", line 15, in setup_hook
    for file in os.listdir(cwd + '/cogs'):
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\Users\\ego\\Documents\\Development\\Discord\\murder\\utils/cogs'
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001BFF91525E0>
Traceback (most recent call last):
  File "C:\Users\ego\anaconda3\lib\asyncio\proactor_events.py", line 116, in __del__
    self.close()
  File "C:\Users\ego\anaconda3\lib\asyncio\proactor_events.py", line 108, in close
    self._loop.call_soon(self._call_connection_lost, None)
  File "C:\Users\ego\anaconda3\lib\asyncio\base_events.py", line 746, in call_soon
    self._check_closed()
  File "C:\Users\ego\anaconda3\lib\asyncio\base_events.py", line 510, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed```
sick birch
#
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\Users\\ego\\Documents\\Development\\Discord\\murder\\utils/cogs'
sacred gull
#

Huh

#

from utils.data import Bot I have this imported to make sure I get the bot class from the data file just so it can work

sick birch
#

Right, but this is a pathing issue

#

I believe it should be

for file in os.listdir(cwd + '\\cogs'):
oak oar
#

for file in os.listdir(cwd + '/cogs'): this part seems to be the issue

sacred gull
oak oar
sacred gull
#

wait, i think i fixed it

#

ok yeah i fixed it

#

thank you guys for your help

#

especially you @sick birch

sick birch
#

it was my pleasure!

sacred gull
#

😄

sinful wind
#

I'm taking a look at pycord. I downloaded the package but I think the library names are conflicting. I have discord.py which is referenced by import discord and I also have pycord which is import discord. How can I change the name of the package?

snow ibex
#

Kinda

#

But it's not recommended

sinful wind
#

what do you recommend

snow ibex
#

Uninstall one of the libraries or make a locked environment

sinful wind
#

I'll uninstall it as I think I will be moving to pycord

slate swan
#

alright

snow ibex
#

Ight

slate swan
#

but i still recommend u to use venv... for all your project.. but still, your choice

#

:")

snow ibex
#

It keeps everything more organized

slate swan
#

yep

#

and u can work with other ppl on their repo without your lib or versions affecting eachother

snow ibex
#

And if you set it up right you won't fill up your c drive with libraries

slate swan
#

^^ +1

#

i've like only 3 libs installed in global env

snow ibex
#

Nice

slate swan
#

:>

sinful wind
#

Kinda weird but after I uninstalled discord.py I now don't have any packages named discord when importing. When I run pip list however I see that py-cord is still there and discord.py is gone

sinful wind
#

yee

slate swan
#

reload your vsc window

sinful wind
#

I have several times

slate swan
#

owo

sinful wind
#

I want to mention I did run pip uninstall discord the first time

slate swan
#

u were suppose to run pip uninstall discord.py

sinful wind
#

I did that the second time

slate swan
#

ok

sinful wind
#

I'm just mentioning incase it matters

slate swan
#

ah ok

#

well do pip list and show me output for a second

sinful wind
slate swan
#

🤔 i see

#

btw why do you have discord-py-slash-command?

slate swan
#

i don't see any problem with it

boreal ravine
#

No spoonfeeding.

sinful wind
#

I can't import py-cord it's invalid syntax

#

and it's not registered under an alternative like pycord

sick birch
sinful wind
#

and all the videos have it registered as import discord

sacred gull
fervent shoal
#
client = discord.Client()
ben = "ben"
ben_response1 = 'yes'
ben_response2 = 'no' 
ben_response3 = 'hohoho'
ben_response4 = 'blehh'

ben_responseULTIMATE = ben_response1, ben_response2, ben_response3, ben_response4
@bot.listen()
async def on_message(message: discord.Message):
    if message.author.bot: return
    for i in ben:
        if message.channel.category.id == 937556857822773281:
            return
        if i in message.content:
            return await message.channel.send(ben_responseULTIMATE)
bot.run(TOKEN)```
#

so recently talking ben was being shut down, so my friends wanted to make a scuff one, this one is basic and just responds to anything and doesnt respond with the right thing either, any tips?

sick birch
#

You need to add more if statements & in the right place to get it to do what you want

#
if i in message.content:
            return await message.channel.send(ben_responseULTIMATE)

sends a message for every letter in any message

fervent shoal
#

any tips on how to fix this?

sick birch
#

You're going to get ratelimited really fast

#

hard to tell what you're trying to do

#

Do you want like trigger words that would make the bot say something?

fervent shoal
#

yes

sick birch
#

use a dict for it

fervent shoal
#

pardon?

sick birch
#
myDict = {
  "triggerWord1": "answer1",
  "triggerWord2": "answer2",
  ...
}
#

All your trigger words and answers are in there

fervent shoal
#

and what would i put in the ben_responseULTIMATE

#
            return await message.channel.send(ben_responseULTIMATE)```
in here
sick birch
#

Then, in your on_message(), you can loop through each word, and check if that word is one of the keys in that dict:

myDict = {
  ...
}

for word in message.content:
  if word in myDict:
    print(myDict[word])
fervent shoal
#

and for the answer, can i have a list?

pliant gulch
#

Your current would iterate characters

sick birch
#

oops yeah

sick birch
fervent shoal
#
async def on_message(myDict = {
  ...
}

for word in message.content:
  if word in myDict:
    print(myDict[word])):```
#

like so @sick birch ?

slate swan
fervent shoal
#

so it should be message.content.split(myDict = {
...
}

for word in message.content:
if word in myDict:
print(myDict[word])
print(myDict[word])):

slate swan
#

nono, you need to use the for loop kn message.content.split

fervent shoal
#

how would i do that

sick birch
#

That loops through each word in the message

#

From there you can check if word in myDict

fervent shoal
#
async def on_message(message):
    for word in message.content.split(' '):

???, sorry if im coming of as really stupid, i am

sick birch
#

Thats the first part correct

#

Now you need to fill in the block of the for loop

#
for word in message.content.split(' '):
  # logic here
boreal ravine
#

they never changed the namespace

fervent shoal
# sick birch Now you need to fill in the block of the for loop
async def on_message(message):
    for word in message.content.split(' '):
        if message.author.bot: return
        for i in ben:
            if message.channel.category.id == 928088528754192446:
                return
        if i in message.content:
            return await message.channel.send()```

something like this? if not then what do i need to replace
sick birch
#

You can move the if message.author.bot: return outside of the loop

#

Same thing with if message.channel.category.id == 928088528754192446: return

fervent shoal
#
async def on_message(message):
    for word in message.content.split(' '):
        for i in ben:
            if i in message.content:
                return await message.channel.send()
sick birch
#
for word in message.content.split(' '):
  if word in myDict:
    # send a response using myDict[word]
  else:
    # ignore, no trigger word
fervent shoal
#

i cant use ctx.send can i

sick birch
#

Sure can

#

ctx.send(myDict[word])

fervent shoal
#

ctx isnt defined, which is why i asked

slate swan
sick birch
#

Oh right

#

Use message.channel to get the channel

slate swan
sick birch
slate swan
#

!e print("a b c".split())

unkempt canyonBOT
#

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

['a', 'b', 'c']
slate swan
#

ig not

sick birch
#

I stand corrected

#

Well, if you want to keep it .split(' ') for the sake of brevity

sinful wind
#

Okay I think I finally resolved my issues with installing pycord except when I installed some of the boilerplate code from the examples folder on their github I am already getting resolution errors as if the discord object I am importing is different from the one they are using:

fervent shoal
#
  "ben": "yes"
  "ben"; "no" }```
slate swan
#

restart vscode,
do you have some other libraries using the discord namespace?

fervent shoal
#

getting the statements are not closed, and expected expressions error

slate swan
fervent shoal
#

so i cant have it cycle through 4 responses for the same triggerword?

slate swan
sick birch
#

^

#

You have to pick which one to send however

sinful wind
fervent shoal
slate swan
sinful wind
#

I have restarted

sick birch
slate swan
fervent shoal
#

so i cant have it choose randomly

sick birch
#

You can

fervent shoal
#

yes sarth

sick birch
#

random.choice()

slate swan
#

!d random.choice use this

unkempt canyonBOT
#

random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
sinful wind
#

Can I just download the discord folder from pycord's github and drop it into my workspace instead?

slate swan
#

ill suggest using a venv instead

fervent shoal
#

where would i put 1random.choice()

sinful wind
#

How long does it take to set up

slate swan
#

a few seconds

fervent shoal
#
async def on_message(message):
    for word in message.content.split(' '):
        if word in myDict:
            await message.channel.send;random.choice()(myDict[word])```
slate swan
# slate swan a few seconds
$python -m pip install virtualenv
$python -m virtualenv <your env name>
# for linux/macOS
$source <your env name>/bin/activate
# for windows
$cd <your env name> 
$.\Scripts\activate``` and then you can pip install in the venv
slate swan
fervent shoal
#

much thanks

paper sluice
#

Hello lads

vale wing
#
from discord.ext.commands import slash_command```
#

You had no issues with libraries

stiff gorge
#

how to change this version ?

Because no versions of discord match >1.7.3,<2.0.0
   and discord (1.7.3) depends on discord.py (>=1.7.3), discord (>=1.7.3,<2.0.0) requires discord.py (>=1.7.3).
  Because discord.py (1.7.3) depends on aiohttp (>=3.6.0,<3.8.0)
   and no versions of discord.py match >1.7.3, discord.py (>=1.7.3) requires aiohttp (>=3.6.0,<3.8.0).
  Thus, discord (>=1.7.3,<2.0.0) requires aiohttp (>=3.6.0,<3.8.0).
  So, because python-template depends on both discord (^1.7.3) and aiohttp (^3.8.1), version solving failed.
slate swan
vast gale
#

👀

vast gale
#

because i can tell you for a fact that discord.ext.commands still exists

stiff gorge
#

i tried to import aiosqlite and aiohttp

vale wing
#

Maybe different version

#

The solution would be to add ext anyways

vale wing
stiff gorge
#

1.7.3

vale wing
#

Try installing 2.0

slate swan
slate swan
#

this is the example they are using it im not wrong

echo wasp
#
if message.content contains link:```  how do i make this work properly with api
high sun
#

You could use in in your if-statement

echo wasp
high sun
#

!e

string = 'https://twitter.com'
if 'https://' in string:
    print("Found")
unkempt canyonBOT
#

@high sun :white_check_mark: Your eval job has completed with return code 0.

Found
boreal ravine
echo wasp
slate swan
#

"in" statment is a very basic python thing

#

Don't be mean

boreal ravine
silver agate
#

ImportError: cannot import name 'PartialMessageable' from 'discord.channel' (c:\Users\ghost\PycharmProjects\pythonProject4\venv\lib\site-packages\discord\channel.py)
tf is this? didnt change anything

slate swan
#

where does this error come from?

echo wasp
high sun
slate swan
silver agate
#

or what do u mean

tawdry perch
slate swan
echo wasp
silver agate
#

code is long

#

xD but traceback sure

silver agate
stiff gorge
#

how to use hybrid_command ?

high sun
#

You might need to upgrade the library

#

What version?

silver agate
#

just installed the newest 3 days ago

#

py-cord 2.0.0b7

boreal ravine
echo wasp
high sun
silver agate
#

I didnt change anything, bot was running and after a while that error came

echo wasp
#
from discord import Webhook, AsyncWebhookAdapter
import aiohttp

async def foo():
    async with aiohttp.ClientSession() as session:
        webhook = Webhook.from_url('url-here', adapter=AsyncWebhookAdapter(session))
        await webhook.send('Hello World', username='Foo')``` what is foo?
high sun
#

Well, that would be the thing that causes the error

high sun
boreal ravine
echo wasp
boreal ravine
#

I know?

echo wasp
#

he showed an example using the !e function

tawdry perch
echo wasp
#

how do i make it so i need to use a command in the bot dms and it doesn't work anywhere else? docs link by chance?

paper sluice
#

check is ctx.channel is an instance of discord.channels.DMChannel

echo wasp
echo wasp
high sun
vale wing
#

Problem with firewall ig

echo wasp
echo wasp
high sun
#

If you’re using on_message you can do a simple if-statement

high sun
#

Just check on ID

echo wasp
#

docs don't say

high sun
#

!d discord.on_message

unkempt canyonBOT
#

discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") is created and sent.

This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled...
echo wasp
high sun
#

!d discord.Message

unkempt canyonBOT
#

class discord.Message```
Represents a message from Discord...
high sun
#

Did you found it, @echo wasp ?

paper sluice
#

!d discord.channel.DMChannel

unkempt canyonBOT
high sun
paper sluice
#

@echo wasp do something like if isinstance(ctx.channel, discord.channel.DMChannel): ...

high sun
#

So check the channel ID of the message

paper sluice
echo wasp
high sun
paper sluice
#

ur telling to check the id, that is not right

high sun
#

I know, but I wanted him to figure it out himself by giving the class

echo wasp
high sun
#

You want it hard coded or the id of the channel of ctx?

paper sluice
high sun
paper sluice
#

they only wanted it to work in dms

echo wasp
echo wasp
paper sluice
#

👀

echo wasp
paper sluice
#

i gues u can do this if isinstance(ctx.channel, discord.channel.DMChannel) and ctx.author.id == <user_id>

echo wasp
paper sluice
#

um then use that

echo wasp
paper sluice
#

what username slot?

echo wasp
#
from discord import Webhook, AsyncWebhookAdapter
import aiohttp

async def foo():
    async with aiohttp.ClientSession() as session:
        webhook = Webhook.from_url('url-here', adapter=AsyncWebhookAdapter(session))
        await webhook.send('Hello World', username='Foo')```
#

that one

echo wasp
high sun
#

You can't use a webhook to send a DM

echo wasp
echo wasp
slate swan
#

bruh 🤯

#

!d discord.Client.fetch_webhook use this

unkempt canyonBOT
#

await fetch_webhook(webhook_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Retrieves a [`Webhook`](https://discordpy.readthedocs.io/en/master/api.html#discord.Webhook "discord.Webhook") with the specified ID.

Changed in version 2.0: `webhook_id` parameter is now positional-only.
echo wasp
#

is a webhook counted as a bot?

vale wing
#

Webhook is webhook wdym

slate swan
#

what does inline mean?

echo wasp
slate swan
#

yea

#

i`m make server info

echo wasp
# slate swan yea

it means right next to the other feild if inline is false it goes underneath it

slate swan
#

and i don`t know what is inline

echo wasp
slate swan
#

how can i show the number of bots on the server?

#

exactly the quantity

echo wasp
#

len(list(filter(lambda x: x.bot, guild.members)))

slate swan
#

thx

echo wasp
stiff gorge
#
 File "/home/runner/Mavic-New-1/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 693, in _parse_arguments
    raise discord.ClientException(fmt.format(self))
discord.errors.ClientException: Callback for balance command is missing "ctx" parameter.
  @commands.command(aliases=['bal'])
  async def balance(ctx):
    await open_account(ctx.author)
    user = ctx.author
    users = await get_bank_data()
    wallet_amt = users[str(user.id)]["wallet"]
    bank_amt = users[str(user.id)]["bank"]
    em = discord.Embed(title=f'{ctx.author.name} Balance',
                       color=discord.Color.red())
    em.add_field(name="Wallet", value=wallet_amt)
    em.add_field(name='Bank', value=bank_amt)
    await ctx.send(embed=em)
#

is anything wrong in this ?

high sun
#

Are you using classes?

slate swan
#

can I not write value in embed?

#

i just need a name

junior verge
#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed...
slate swan
#

when I write None it says so

unkempt canyonBOT
#

Colour your text / terminal to be more gay. 🏳️‍🌈

small sentinel
#

Hello, I'm looking for some help, in my discord bot, I create a text channel on the server, but I would like to get the id of the channel I just created to use it later on, any way I could do that please ?

slate swan
#

show ur code btw

small sentinel
#

uhhh

#

I'm not sure you want to see it but let's go

#
@bot.command()
async def rejoindre(ctx,royaume):
    if partie_on == True:
        if royaume in royaumes[1:7]:
            identif = ctx.author.id
            try :
                pickle_ouverture = open (f"fiche de {identif}","rb")
                if load(ctx.author.id)['royaume'] == royaume: 
                    await ctx.send("Tu as déjà rejoint ce royaume.")
                else:
                    await ctx.send(f"2")
                    fiche = load(ctx.author.id)
                    await ctx.author.remove_roles(discord.utils.get(ctx.guild.roles, name = fiche['royaume']), atomic=True)
                    fiche['royaume'] = royaume
                    save(ctx.author.id,fiche)
                    await ctx.author.add_roles(discord.utils.get(ctx.guild.roles, name = royaume), atomic=True)
                    tep(ctx.author.id,"".join(['c',royaume[0].lower()]))
                    liste = load("".join(["liste_",fiche['royaume']]))
                    liste.remove(ctx.author.id)
                    save(liste, "".join(["liste_",fiche['royaume']]))
                    liste = load("".join(["liste_",royaume]))
                    liste.append(ctx.author.id)
                    save(liste,"".join(["liste_",royaume]))
                    await discord.utils.get(ctx.guild.channels, id = categories_royaumes[royaume]).create_text_channel(name='{}'.format(f'fiche-{ctx.author.name}'))
                    await ctx.send(f"{ctx.author.name} a bien rejoint le royaume de {royaume}")
                    return
#
             except :
                await ctx.send(f"1")
                dico_joueur = {'hp':3,'po':500,'tp':0,'mont':montures[0],'role':roles[0],'comp':competences[0],'bgmt':[bourgs[0]], "royaume": royaume}
                save(identif,dico_joueur)
                await discord.utils.get(ctx.guild.categories, id = categories_royaumes[royaume]).create_text_channel(name='{}'.format(f'fiche-{ctx.author.name}'))
                await ctx.send(f"{ctx.author.name} a bien rejoint le royaume de {royaume}")
                await ctx.author.add_roles(discord.utils.get(ctx.guild.roles, name = royaume), atomic=True)
                tep(ctx.author.id,"".join(['c',royaume[0].lower()]))
                try: 
                    liste = load("liste_joueurs")
                    liste.append(ctx.author.id)
                    save("liste_joueurs", liste)
                except: 
                    liste = [ctx.author.id]
                    save("liste_joueurs", liste)
                try: 
                    liste = load("".join(["liste_",royaume]))
                    liste.append(ctx.author.id)
                    save("".join(["liste_",royaume]), liste)
                except: 
                    liste = [ctx.author.id]
                    save("".join(["liste_",royaume]), liste)
                return
        else:
            await ctx.send(f":warning: {royaume} n'est pas un royaume. Attention à l'orthographe, la liste des royaume est: {', '.join(royaumes[1:7])}")
            return
slate swan
#

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

small sentinel
# slate swan show ur code btw

The channel which I want to get the id is the channel I create in

await discord.utils.get(ctx.guild.categories, id = categories_royaumes[royaume]).create_text_channel(name='{}'.format(f'fiche-{ctx.author.name}'))
#

not the channel in which I write the rejoindre command

slate swan
#
a = await discord.utils.get(ctx.guild.categories, id = categories_royaumes[royaume]).create_text_channel(name='{}'.format(f'fiche-{ctx.author.name}'))
print(a.id)

not sure but try

tiny ibex
#

Hey is there a way the bot can use the Slash command of another bot?

#

In dpy 1.7.3

small sentinel
#

I don't even know what f string is

#

this is like the first python 'script' I make

slate swan
#

no way

#

u copy pasted

#

right?

small sentinel
#

what did I copy paste

slate swan
#

u used f string in . format

small sentinel
#

yes

#

a friend of mine told me to use the f thing for channel names I think

#

so I used it

tiny ibex
small sentinel
#

writing a discord bot is my way of learning python

#

this bot will probably never run on a real server

#

it's just a training dummy

tiny ibex
small sentinel
#

¯_(ツ)_/¯

#

opinion rejected

tiny ibex
small sentinel
#

I do understand python lmao

gaunt ice
#

hm

tiny ibex
#

if you did you would be knowing bout f strings

small sentinel
#

I do know about f strings I use them in my code

gaunt ice
#

..

small sentinel
#

I just didn't know they were called f strings

#

anyway my question was answered theres literally no reason for us to talk

slate swan
small sentinel
#

this part was copy pasted from my friend

slate swan
#

whats the issue?

slate swan
slate swan
boreal ravine
#

Sparky stop

slate swan
tiny ibex
boreal ravine
slate swan
boreal ravine
#

only users can

tiny ibex
slate swan
unkempt canyonBOT
#
Nuh-uh.

No documentation found for the requested symbol.

tiny ibex
#

that will work?

boreal ravine
#

??

slate swan
#

no

#

!pip discord-py-slash-command

unkempt canyonBOT
tiny ibex
#

But how do i send the command

#

??????

slate swan
#

its just how u do selfbotting

slate swan
# unkempt canyon

use this library if you want to but i recommend upgrading to 2.0 @tiny ibex

tiny ibex
slate swan
#

huh?

tiny ibex
#

there is no example on how to do that!

slate swan
tiny ibex
slate swan
#

listen bot cant use slash commands

#

thats it

#

you wanted another bot's slash commands....?

slate swan
#

he want to run a slah command of another bot with his bot

#

idk

tiny ibex
#

yes

slate swan
#

if we can or not

#

uh yeah that cannot be

slate swan
tiny ibex
#

how does the discord client do it.......

slate swan
#

dont selfbot

tiny ibex
#

tf?

slate swan
slate swan
#

app commands, profiles, badges, connections, friends being some of them

#

ok

tiny ibex
#

Uhh ok

#

Well i was trying to create a mod

slate swan
#

bruh

#

make ur own mod bot

tiny ibex
#

It's against ToS

#

Ik ik

supple thorn
supple thorn
tiny ibex
#

anyways

#

wanted to create something like discurses

slate swan
tiny ibex
slate swan
#

😔

stiff gorge
# maiden fable U forgot self

i get this error whn i type self

 File "/home/runner/Mavic-New-1/cogs/economy.py", line 35, in balance
    await open_account(ctx.author)
  File "/home/runner/Mavic-New-1/data.py", line 32, in open_account
    await loop.run_in_executor(None,inthread)
AttributeError: 'builtin_function_or_method' object has no attribute 'run_in_executor'

data.py

    def inthread():
      try:
        glock.acquire()
        with open('mainbank.json','w') as f:
          json.dump(users,f)
      finally:
        glock.release()
    loop = asyncio.get_running_loop
    await loop.run_in_executor(None,inthread)

    return True
tiny ibex
slate swan
sullen pewter
#

How can I fix the error?

silver wolf
sullen pewter
#

the error occurs when I run the bot

silver wolf
#

"names must be all lower case"

name=Ban
name=ban

Lowercase

sullen pewter
#

o

silver wolf
#

np

small sentinel
#

helo again

#

I have a problem with a command

#
@bot.command()
async def fiche(ctx):
    if partie_on == True:
        if int(ctx.channel.id) == int(load("identifiants_fiches")[ctx.author.id]):
            a = load(ctx.author.id)
            inv = a['inv']
            finv = ", ".join(inv)
            eqp = a['eqp']
            feqp = ", ".join(eqp)
            embed=discord.Embed(title="Fiche Personnelle")
            embed.add_field(name="Points de vie:", value=f"{a['hp']} :drop_of_blood:", inline=True)
            embed.add_field(name="Pièces d'or:", value=f"{a['po']} :pofix:", inline=True)
            embed.add_field(name="Trésorerie perso:", value=f"[ {a['pt']} :pofix: ]", inline=True)
            embed.add_field(name="Rôles:", value=a['role'], inline=True)
            embed.add_field(name="Compétence:", value=a['comp'], inline=True)
            embed.add_field(name="Bourgmestre de:", value=a['bgmt'], inline=True)
            embed.add_field(name="Localisation:", value=a['tp'], inline=True)
            embed.add_field(name="Monture:", value=a['mont'], inline=True)
            embed.add_field(name="pods:", value=a['pods'], inline=True)
            embed.add_field(name="Ressources:", value=f"{a['fer']} :fer: / {a['pierre']} :pierre: / {a['acier']} :acier: / {a['bois']} :bois: / {a['herbe']} :herbe: / {a['argent']} :argent:", inline=False)
            embed.add_field(name="Inventaire:", value=finv, inline=False)
            embed.add_field(name="Equipement:", value=feqp, inline=False)
            await ctx.send(embed=embed)
#

here's the error I get:

Ignoring exception in command fiche:
Traceback (most recent call last):
  File "C:\Users\xxxxx\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\xxxxx\Documents\Perso\Perso\Python\bot furiat\bot.py", line 235, in fiche
    await ctx.send(embed=embed)
  File "C:\Users\xxxxx\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\abc.py", line 1065, in send
    data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
  File "C:\Users\xxxxx\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 254, in request
    raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.10.value: This field is required
In embed.fields.11.value: This field is required

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\xxxxx\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\xxxxx\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\xxxxx\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.10.value: This field is required
In embed.fields.11.value: This field is required
#

the problem seems to be the .join() format

#

load("identifiants_fiche") is a dictionary of lists

small sentinel
#

returns []

#

bc the inventory of the player is empty

green bluff
#

dont think you can join empty lists

small sentinel
#

I test with a full list

#

it works thanks

green bluff
amber lynx
#

how do i give an error for missing an argument?

#

i am using @client.command btw

supple thorn
unkempt canyonBOT
#

exception discord.ext.commands.MissingRequiredArgument(param)```
Exception raised when parsing a command and a parameter
that is required is not encountered.

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

Use this error to send what you want

small sentinel
#

I think you can do

async def command(ctx, argument='something')
  if argument == 'something':
    send your error
supple thorn
paper sluice
#

= -> assignment operator
== -> equality check operator

supple thorn
amber lynx
#

i just want to check if the argument is empty and if it is then give error

supple thorn
#

Just have a error handler

amber lynx
supple thorn
unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied mute to @slate swan until <t:1651230820:f> (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).

stiff gorge
#
  Because no versions of discord match >1.7.3,<2.0.0
   and discord (1.7.3) depends on discord.py (>=1.7.3), discord (>=1.7.3,<2.0.0) requires discord.py (>=1.7.3).
  Because discord.py (1.7.3) depends on aiohttp (>=3.6.0,<3.8.0)
   and no versions of discord.py match >1.7.3, discord.py (>=1.7.3) requires aiohttp (>=3.6.0,<3.8.0).
  Thus, discord (>=1.7.3,<2.0.0) requires aiohttp (>=3.6.0,<3.8.0).
  So, because python-template depends on both discord (^1.7.3) and aiohttp (^3.8.1), version solving failed.
#

i just imported aiohttp i got this error

flint isle
#

Disregard. I misread the docs

@bot.command(name='button')
async def button(ctx):
    await ctx.send(
        "Hello, World!",
        components = [
            Button(label = "WOW button!", custom_id = "button1")
        ]
    )

    interaction = await bot.wait_for("button_click", check = lambda i: i.custom_id == "button1")
    await interaction.send(content = "Button clicked!")

I keep getting "This interaction failed"

green bluff
#

anybody know

#

what the embed hex code is like the embed it self

stiff gorge
flint isle
stiff gorge
paper sluice
#

Buttons (or components) are now in the 2.0a version of the library which is only obtainable from GitHub.

If you wish to use Buttons (and Selects/Dropdowns), please view the documentation for discord.ui here: https://discordpy.readthedocs.io/en/master/api.html#bot-ui-kit

You can also view examples in the repo: https://github.com/Rapptz/discord.py/tree/master/examples/views

GitHub

An API wrapper for Discord written in Python. Contribute to Rapptz/discord.py development by creating an account on GitHub.

stiff gorge
#

how do i get aiohhtp 3.6.0 ?

Installing collected packages: frozenlist, async-timeout, aiosignal, aiohttp, discord2
  Attempting uninstall: async-timeout
    Found existing installation: async-timeout 3.0.1
    Uninstalling async-timeout-3.0.1:
      Successfully uninstalled async-timeout-3.0.1
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
discord-py 1.7.3 requires aiohttp<3.8.0,>=3.6.0, but you have aiohttp 3.8.1 which is incompatible.
Successfully installed aiohttp-3.8.1 aiosignal-1.2.0 async-timeout-4.0.2 discord2-2.0.1 frozenlist-1.3.0
paper sluice
#

pip install aiohttp==<version>

stiff gorge
#

ty

slate swan
stiff gorge
#

but the bot dosent run

slate swan
#

weird

jade tartan
#

Someone help plz

paper sluice
#

Um remove the author name?

slate swan
paper sluice
#

Why do u have it there if u don't want?

stiff gorge
jade tartan
stiff gorge
#

it says some aiohttp version dosent match

paper sluice
#

How do u remove embeds on phone 😢

stiff gorge
# slate swan weird
Updating dependencies
Resolving dependencies...

  SolverProblemError

  Because no versions of discord match >1.7.3,<2.0.0
   and discord (1.7.3) depends on discord.py (>=1.7.3), discord (>=1.7.3,<2.0.0) requires discord.py (>=1.7.3).
  Because discord.py (1.7.3) depends on aiohttp (>=3.6.0,<3.8.0)
   and no versions of discord.py match >1.7.3, discord.py (>=1.7.3) requires aiohttp (>=3.6.0,<3.8.0).
  Thus, discord (>=1.7.3,<2.0.0) requires aiohttp (>=3.6.0,<3.8.0).
  So, because python-template depends on both discord (^1.7.3) and aiohttp (^3.8.1), version solving failed.

  at venv/lib/python3.8/site-packages/poetry/puzzle/solver.py:241 in _solve
      237│             packages = result.packages
      238│         except OverrideNeeded as e:
      239│             return self.solve_in_compatibility_mode(e.overrides, use_latest=use_latest)
      240│         except SolveFailure as e:
    → 241│             raise SolverProblemError(e)
      242│ 
      243│         results = dict(
      244│             depth_first_search(
      245│                 PackageNode(self._package, packages), aggregate_package_nodes
/home/runner/Mavic-New-1/venv/lib/python3.8/site-packages/setuptools/command/install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
  warnings.warn(
exit status 1

do u know wht is causing this im not able to figure it

slate swan
stiff gorge
buoyant zodiac
#
  1. something
#

who uses python 2.0

paper sluice
buoyant zodiac
#

2.0 python came out in like 2006 bruh

slate swan
#

but....smh smhhhh

slate swan
stiff gorge
#

how do i install 3.8 ?

buoyant zodiac
#

toh should try and use a newer version

#

go to their website @stiff gorge

stiff gorge
#

pip install discord.py==3.8.0 ??

buoyant zodiac
buoyant zodiac
jade tartan
slate swan
boreal ravine
#

no

#

that's disnake

slate swan
#

no

#

if I remember correctly

boreal ravine
#

what?

slate swan
#

Aliases possible in command group?

boreal ravine
boreal ravine
slate swan
slate swan
sage otter
#

It’s the same as regular commands

#

You just feed aliases into the group decorator

sage otter
jade tartan
#
async def start(ctx):
    embed=discord.Embed(title="Profile", description="", color=0x00ff00)
    embed.add_field(name= f"User: {ctx.author.mention}", value="✅Verified 18+✅", inline=False)
    embed.add_field(name='Name', value=str(ctx.author.name), inline=True)
    embed.add_field(name='Age', value="", inline=True)
    embed.add_field(name='Gender', value="", inline=True)
    embed.add_field(name='Orientation', value="", inline=True)
    embed.add_field(name='Location', value="", inline=True)
    embed.add_field(name='Dating status', value="", inline=True)
    embed.add_field(name='Height', value="", inline=True)
    embed.add_field(name='DMs status', value="", inline=True)
    embed.add_field(name='Verification level', value="", inline=True)
    embed.add_field(name='Looking for', value="", inline=True)
    embed.add_field(name='Hobbies', value="", inline=True)
    embed.add_field(name='About me', value="", inline=True)
    embed.set_author(name=ctx.author.name, icon_url= ctx.message.author.avatar_url)
    await ctx.send(embed=embed)```
sage otter
#

() pls

jade tartan
#

Is this right?

sage otter
#

Try It And See

slate swan
sage otter
slate swan
sage otter
#

@commands.group(aliases=["1", "2", "3"])

slate swan
#

Please help me while i playing next song in queue i got this error
TypeError: on_wavelink_track_end() missing 1 required positional argument: 'player'
This is an wavelink track end code

async def on_wavelink_track_end(ctx: commands.Context, player: wavelink.Player, track: wavelink.Track, reason):
        ctx = player.ctx
        vc: player = ctx.voice_client

        if vc.loop:
            return await vc.play(track)
        
        next_song = vc.queue.get()
        await vc.play(next_song)
        await ctx.send(f"Now playing {next_song.title}")```
slate swan
jade tartan
#
async def start(ctx):
    embed=discord.Embed(title="Profile", description="", color=0x00ff00)
    embed.add_field(name= f"User: {ctx.author.mention}", value=":white_check_mark:Verified 18+:white_check_mark:", inline=False)
    embed.add_field(name='Name', value=str(ctx.author.name), inline=True)
    embed.add_field(name='Age', value="", inline=True)
    embed.add_field(name='Gender', value="", inline=True)
    embed.add_field(name='Orientation', value="", inline=True)
    embed.add_field(name='Location', value="", inline=True)
    embed.add_field(name='Dating status', value="", inline=True)
    embed.add_field(name='Height', value="", inline=True)
    embed.add_field(name='DMs status', value="", inline=True)
    embed.add_field(name='Verification level', value="", inline=True)
    embed.add_field(name='Looking for', value="", inline=True)
    embed.add_field(name='Hobbies', value="", inline=True)
    embed.add_field(name='About me', value="", inline=True)

Can someone help me

slate swan
#

but.. what help u need? :")

#

what error you got?

#

or are u just showing your code? :")

sage otter
#

If that’s actually your code

#

You can’t use it because all your fields values are empty

jade tartan
#

and i want it to show

slate swan
jade tartan
#

OK well i am trying to add ppls age as an embed profile

paper sluice
sage otter
#

no

#

Why would that work.

jade tartan
#

Do how know how to write in sqlite db?

#

type

sage otter
#

Discord fields require a name and value

paper sluice
#

u can't add fields without values?

slate swan
slate swan
#

value is required.. even i didn't know

#

just got to knwo about it a few minutes ago when tylerr told

sage otter
#

Why would it not be ooogh

#

you just gonna have fields with a name.

slate swan
slate swan
slate swan
sage otter
#

why are you gonna try to use a sql based database without knowing sql

#

That’s like the same principle as trying to learn dpy with no python knowledge

slate swan
#

i think he knows SQL and doesn't knowhow to use sqlite..

#

maybe

sage otter
#

It’s literally the same thing as any other database

slate swan
#

yeah just connector & execute, fetch things..

sage otter
#

cursor

jade tartan
sage otter
#

you need a cursor

jade tartan
#

First time

slate swan
jade tartan
#

I mean i learn from other ppl

#

Its better that way

slate swan
#

there should be some demonstration of how ot use it

#

i'm only familliar with asyncpg & mysql-connector-python

slate swan
slate swan
sage otter
#

sqlite is probably easier than postgres

#

you’d probably find it mad easy

slate swan
#

well i can agree

#

postgres took me like hours to get its grip tho i was already familiar with mysql

slate swan
#

So here’s the thing
I got my bot prefix as a? I want the bot to respond to a? & A?

#

Possible?

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a discord bot.

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result
anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with
this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality
to manage commands...
slate swan
#
case_insensitive = True
``` @slate swan
maiden fable
sage otter
#

That applies to commands

jade tartan
#

Do you know whats the module to install for sqlite?

#

is it pip install sqlite

maiden fable
unkempt canyonBOT
maiden fable
#

For async sqlite

slate swan
sage otter
#

No literally just set a second prefix

maiden fable
slate swan
#

....

sage otter
#

Well command_prefix takes a list of prefixes

#

Just add

maiden fable
slate swan
maiden fable
#

Like this add yr prefixes

slate swan
slate swan
maiden fable
slate swan
#

🤔 it doesn't work for prefixes?

maiden fable
#

!d discord.ext.commands.Bot.case_insensitive

unkempt canyonBOT
#

Whether the commands should be case insensitive. Defaults to False. This
attribute does not carry over to groups. You must set it to every group if
you require group commands to be case insensitive as well.

maiden fable
#

"Whether the commands should be case sensitive"

slate swan
#

aahh looks like i've forgotten about prefix command shit.. since i moved to slash 😭

#

💀

maiden fable
#

That's what I'm tryna tell u since the start smh

slate swan
sage otter
#

slash = trash

slate swan
#

nvm

#

😂

jade tartan
#

con = sqlite3.connect('example.db')
cur = con.cursor()

cur.execute('''CREATE TABLE IF NOT EXISTS AGE
(age text)''')

con.commit()``` Am i on the right track?
maiden fable
#

Not funny

sage otter
#

I can imagine.

slate swan
slate swan
maiden fable
#

Aaaa

slate swan
#

but.. it went wrong.. so nvm

sage otter
#

Bad context.

maiden fable
#

I thought u meant to reply to the message "slash = trash"

slate swan
#

💀 bruh

maiden fable
#

My bad

sage otter
#

I can acknowledge the fact I’m trash too

slate swan
#

ok whatever u wanna think :")

maiden fable
#

Since u edited it too

small sentinel
#

Helo again, I put a discord.py command in a function which wasn't in async, it it very dangerous ? or I can leave 1 or 2 discord.py commands in non-async functions

def tep(target, destination='∅'):
    fish = load(target)
    channel = bot.get_channel(channels_bourgs[fish['tp']])
    fish['tp'] = destination
    save(target, fish)
    overwrite = discord.PermissionOverwrite()
    overwrite.send_messages = False
    overwrite.read_messages = True
    cible = bot.get_user(target)
    channel.set_permissions(cible, overwrite=overwrite)

Error:

c:\Users\xxxxx\Documents\Perso\Perso\Python\bot furiat\bot.py:331: RuntimeWarning: coroutine 'GuildChannel.set_permissions' was never awaited
  channel.set_permissions(cible, overwrite=overwrite)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
slate swan
slate swan
#

but still they make things somewhat easier

maiden fable
#

I agree

small sentinel
#

guys read my text pls 💀

slate swan
#

which one? 💀

slate swan
#

oh nvm i'm blind 😂

small sentinel
#

well it does

maiden fable
#

Python error. U can use await inside an async function

small sentinel
#

I didn't await and I used it in a non-async function

#

so it still did the stuff, but I got an error

sage otter
#

only thing that’s relatively good about slash commands is the auto-complete aspect

#

That’s the only thing that regular message commands won’t be able to beat

#

And probably the pre-set answers

slate swan
#

and u can set input whether it shuold be optional or required..

#

so.. 👀 it is a life saver in some ways

small sentinel
sage otter
#

so it’s basically like

#

An aid for people who can’t read help text

slate swan
#

tho yeah.. a lil bit pain for devs :")

slate swan
sage otter
#

That’s crazy .

small sentinel
#

¯_(ツ)_/¯

#

ohhh wait

sage otter
#

I doubt that’s what happened

small sentinel
#

no no

sage otter
#

Python won’t let that happen.

small sentinel
#

it didn't happen lmao

#

ty

slate swan
#

u can ping btw. i don't bite

sage otter
#

Message commands all the way to the end yay

sage otter
slate swan
#

😂 alright

slate swan
#

hello

obsidian glade
#

ok look

small stump
#

@slate swan ```py
@client.event
async def on_message(message, searchKey):
if searchKey in message.content.lower().strip():
await message.delete()

obsidian glade
#

in a code

small stump
#

may i suggest something like this? this way u dont need more events

obsidian glade
#

searchkey?

slate swan
#

my words

small stump
#

ohh wait nvm

dusky pine
#

also, probably should also use snake_case 😅

small stump
#

yeah i realized haha

small sentinel
#

Hi again

async def tep(target, destination='∅'):
    fish = load(target)
    channel = bot.get_channel(channels_bourgs[fish['tp']])
    fish['tp'] = destination
    save(target, fish)
    cible = bot.get_user(target)
    await channel.set_permissions(cible, send_messages = False)

(the problem isn't channel because everything works when I replace set_permissions with send("test")

dusky pine
slate swan
#

)) but why if I said this, it actives only second

@client.event
async def on_message(message):
    if "lol" in message.content.lower():
        await message.delete()

@client.event
async def on_message(message):
    if "haha" in message.content.lower():
        await message.delete()
small sentinel
dusky pine
#

Something like
!tep @small sentinel
would work

#

It won't work if you're doing !tep Ukos

paper sluice
small sentinel
#

it's not a discord command

#

it's a python command

dusky pine
slate swan
small sentinel
small stump
#

i feel like (no offense) u dont understand whats going on, just pretty much asking us to write your code for you

this is purely an observation and i wish u luck with it, but i strongly recommend you learn more python first, just for your own good to avoid countless headaches

paper sluice
dusky pine
small stump
#

^^

dusky pine
paper sluice
#

!e

print('hello world' in ('hello', 'world'))
unkempt canyonBOT
#

@paper sluice :white_check_mark: Your eval job has completed with return code 0.

False
dusky pine
#

oh yeah

paper sluice
#

i c the prob, i forgot to split in my example

small sentinel
dusky pine
slate swan
#

Back

small sentinel
#
Ignoring exception in command tp:
Traceback (most recent call last):
  File "C:\Users\achil\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\achil\Documents\Perso\Perso\Python\bot furiat\bot.py", line 333, in tp
    await tep(target, destination)
  File "c:\Users\achil\Documents\Perso\Perso\Python\bot furiat\bot.py", line 320, in tep
    await channel.set_permissions(cible, send_messages = False)
  File "C:\Users\achil\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\abc.py", line 648, in set_permissions
    raise InvalidArgument('target parameter must be either Member or Role')
discord.errors.InvalidArgument: target parameter must be either Member or Role

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\achil\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\achil\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\achil\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: InvalidArgument: target parameter must be either Member or Role
small sentinel
slate swan
#

Code

small sentinel
#

CODE PART 2:

@bot.command()
async def tp(ctx, target='∅', destination='∅'):
  await tep(target, destination)

(target is a user-id and destination is a string)

#

The error seems to be about the parameters of the set_permissions function but cible is a user so I don't understand why he isn't happy

limber stratus
#

Is there any way to scrape members from a Discord server?

quaint epoch
limber stratus
quaint epoch
#

i'll someone else take it from here, ashley or hunter, since i have a geo test

slate swan
# slate swan Code

do yk how to check the onne who clicked on the button im using on message event + and i subclassed the disnake.ui.View

#
@client.command()
async def operator(ctx):
  m = await ctx.send(content="Loading calculator")
  expression = "None"
  delta = datetime.utcnow() + timedelta(minutes = 5)
  e = discord.Embed(title="Basic Operation Calculator",description=expression)
  await m.edit(components=buttons, embed=e)
  while True :
    res = await client.wait_for("button click")
  while m.created_at < delta :
    if res.author.id == int(res.message.embeds[0].title.split("|")[1]) and res.message.embeds[0].timestamp < delta:
      expression = res.message.embeds[0].description
      if expression == "None" or expression == 'An error occurs':
        expression = ''
      elif res.component.label == 'Exit':
        await res.respond(content='Calculator Closed. Thanks for using Basic Operation Calculator.',type=7)
        break
      elif res.component.label == "←":
        expression = expression[:-1]
      elif res.component.label == 'Clear':
        expression = None
      elif res.component.label == '=':
        expression += calculator(expression)
      else:
        expression = res.component.label
      f = discord.Embed(title='Basic Operation Calculator',description=expression)
      await res.respond(content='', embed = f, component=buttons, type=7)

no errors in console
button says interaction failed

quaint epoch
#

you didn't add a callback/didn't defer

#

!d disnake.InteractionResponse.defer

unkempt canyonBOT
#

await defer(*, ephemeral=False, with_message=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Defers the interaction response.

This is typically used when the interaction is acknowledged and a secondary action will be done later.
quaint epoch
#

do this if the process takes longer than 3 seconds

pseudo portal
#
@bot.bridge_command(description = "Just testing")
async def test-one(ctx):
        embed = discord.Embed(
            description="Test Accomplished! 😎",
            colour=discord.Colour.teal()
        )
 
        await ctx.respond(embed=embed)```
why when i do `async def test-one` it doesnt work, but when i do without the dash (`testone`) it does.. how can i use two words? ![think](https://cdn.discordapp.com/emojis/846423939558801488.webp?size=128 "think")
velvet compass
#

Also known as snake_case

pseudo portal
regal pulsar
paper sluice
#

^[^\d\W]\w+ 😳

regal pulsar
#

also you need to add client.process_commands(message)

pseudo portal
#

is there a way to use a dash and not an underschore

regal pulsar
#

then do this

paper sluice
pseudo portal
#

ooh like _ = -?

limber stratus
#

What is the official Discord API through which I can fetch members of any discord server?

paper sluice
regal pulsar
#
@bot.command()
async def buy(ctx: commands.Context, option: str):
    if option == "crypto":
        do-this
    elif option == "something-else":
        do this instead
pseudo portal
pseudo portal
pseudo portal
regal pulsar
#
@bot.command(name='buy-crypto', aliases=['anything'])
async def test_one(ctx):
        embed = discord.Embed(
            description="Test Accomplished! 😎",
            colour=discord.Colour.teal()
        )
 
        await ctx.respond(embed=embed)
regal pulsar
paper sluice
regal pulsar
#

it modifies your function so it works as a command

#

so pass in aliases

#

which are alternative names for your command

silk rock
pseudo portal
limber stratus
regal pulsar
#

you can use any wrapper you want

regal pulsar
pseudo portal
pseudo portal
#

can i do somma like dash = - i mean i doubt itd work tho lol

slate swan
limber stratus
# silk rock yes
import discord
intents = discord.Intents.default(members=True)
client = commands.Bot(command_prefix = prefix, intents=intents)

class MyClient (discord.Client):
    async def on_ready(self):
        guild = client.get_guild(server id)
        print ("ich bin online beep")
        for member in guild.members:
            print (guild.members)```
Will this work?
pseudo portal
silk rock
#

you have to specify it

slate swan
regal pulsar
jade tartan
#

cur.execute('''INSERT OR IGNORE INTO AGE VALUES ('1','2','','','')''') is this where i would add number values?

silk rock
pseudo portal
regal pulsar
slate swan
limber stratus
pseudo portal
regal pulsar
limber stratus
slate swan
regal pulsar
slate swan
limber stratus
limber stratus
regal pulsar
#

yeah thats against tos

slate swan
#

back

regal pulsar
#

and something tells me this isnt your main lol

limber stratus
slate swan
silk rock
regal pulsar
#

unless you use a bot you're gonna get banned

slate swan
#

is @limber stratus alt ?

regal pulsar
regal pulsar
slate swan
slate swan
regal pulsar
#

he's trying to use a user account

slate swan
#

that's against Tos then

regal pulsar
#

apart from it being against tos

quaint epoch
regal pulsar
#

that also wont work

slate swan
#

that will,

regal pulsar
regal pulsar
slate swan
limber stratus
#

Damn, this is confusing.

regal pulsar
#

so you need to use an older version

slate swan
silk rock
regal pulsar
#

second you need to pass in some extra arguments to commands.Bot and bot.run

slate swan
#

HI

regal pulsar
#

you also cant use commands like you do with a bot

slate swan
#

i didnt mention the arguments for that purpose, if you can see it

#

dont selfbot its against tos

slate swan
regal pulsar
#

yeah i know

silk rock
slate swan
regal pulsar
#

he doesnt know python

slate swan
slate swan
regal pulsar
#

he needs to learn that first

slate swan
#

sparky with his message edits

slate swan
limber stratus
regal pulsar
gloomy sandal
#

Is self bot allowed?

regal pulsar
#

for a bot

silk rock
slate swan
regal pulsar
gloomy sandal
#

Lol

#

I actually used it once without knowing that it's not allowed lel

limber stratus
gloomy sandal
#

Yeah I won't now haha

paper sluice
regal pulsar
# limber stratus Please, you are GOD in disguise
import discord
from discord.ext import commands

prefix = "!"
bot = commands.Bot(command_prefix=prefix)


@bot.event
async def on_ready():
    print(f"Logged In As {bot.user}")


@bot.command()
async def members(ctx: commands.Context):
    for member in ctx.guild:
        print(member)


bot.run("token")
regal pulsar
silk rock
regal pulsar
#

log in and click new application

slate swan
regal pulsar
#

go to bot and create bot

#

then click reset token and copy it

regal pulsar
#

my failed creations 😔

#

except joy

slate swan
#

i need to delete many of them

regal pulsar
regal pulsar
slate swan
#

i have 2

slate swan
regal pulsar
#

you cant delete bot accounts

slate swan
#

u can

slate swan
# regal pulsar you cant

you cant delete a bot, but you can delete the application and the bot gets deleted automatically

regal pulsar
#

i see

regal pulsar
#

lol

slate swan
#

!remix

silk rock
#

how do i maks something like this

#

make*

paper sluice
#

!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
slate swan
silk rock
slate swan
#

👀

silk rock
slate swan
regal pulsar
slate swan
#

!pip jishaku

unkempt canyonBOT