#discord-bots

1 messages · Page 1153 of 1

cold sonnet
#

when I do ctrl + ö in visual studio code the terminal pops up

slate swan
#

me for no reason

vocal snow
#

I would recommend starting with a simpler project... especially if you're planning to meddle with voice

cold sonnet
slate swan
novel prairie
#

can someone tell me where i find terminal

slate swan
#

depends on ur os

cold sonnet
#

where do you edit the code

novel prairie
#

im using replit

vocal snow
#

inb4 replit

slate swan
#

go to shell lmao

vocal snow
#

NOOO LATENCY

slate swan
#

if you dont see that option you're probably too ignorant

vocal snow
#

i was not fast enough 😔

cold sonnet
slate swan
#

replit, yes the service which gets its cpu and memory 100% consumed just by poetry update

cold sonnet
novel prairie
#

i found a folder thats named pip and it has a file thats named pip.conf

cold sonnet
#

you don't know how fast I made this replit account

paper sluice
vocal snow
#

somebody needs to make a meme regarding the very common and stereotypical case of python newbie following a swas.py/lucas/carberra tutorial and gluing random code from across the internet in an attempt to become a "professional bot developer"

slate swan
cold sonnet
dusky pine
#

or just go get a VPS and ssh into it

paper sluice
novel prairie
cold sonnet
slate swan
cold sonnet
#

did you hardcode that

slate swan
#

its neofetch

#

a shell command

cold sonnet
#

I don't know what that is

slate swan
cold sonnet
paper sluice
#

atleast use powershell 😭

novel prairie
cold sonnet
cold sonnet
#

it's blue, so what

paper sluice
slate swan
# cold sonnet
iwr -useb get.scoop.sh | iex
scoop install neofetch
scoop install git  # if no git installed
cold sonnet
#

it looks ugly

novel prairie
#

it says this is this right?

#

nstalling collected packages: PyNaCl
Successfully installed PyNaCl-1.4.0

cold sonnet
#

yes

novel prairie
#

ok

cold sonnet
#

that's good

paper sluice
novel prairie
#

can i create a command that says !leave and when im doing this command the bot leaves the vc?

vocal snow
#

!d discord.VoiceClient.disconnect

unkempt canyonBOT
#

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

Disconnects this voice client from voice.
vocal snow
#

@novel prairie ^ you can get the voiceclient through ctx.voice_client or guild.voice_client

novel prairie
#

can you sent me an example on how to do that?

vocal snow
#

do what

novel prairie
#

@bot.command()
async def play(self , ctx, *, song=None):
if song is None:
return await ctx.send("You must include a song to play.")

if ctx.voice_client is None:
  return await ctx.send("I must be in a voice channel to play a song.")

if not ("youtube.com/watch?" in song or "https://youtu.be/" in song):
  await ctx.send("Searching for a song, this may take a few seconds...")

  result = await self.search_song(1, song, get_url=True)

  if result is None:
    return await ctx.send("Sorry, I couldn't find the song you asked for. Try using my search command to find the song you want.")

  song = result[0]

if ctx.voice_client.source is not None:
  queue_len = len(self.song_queue[ctx.guild.id])

  if queue_len < 10:
    self.song_queue[ctx.guild.id].append(song)
    return await ctx.send(f"Song added to the queue at position {queue_len+1}")
  else:
    return await ctx.send("Maximum queue limit has been reached, please wait for the current song to end to add more songs to the queue")
  
await self.play_song(ctx, song)
await ctx.send(f"Now playing: {song}")
#

this is the command for the play

#

and it doesnt work

#

how can i fix it?

slate swan
#

!ytdl moment

unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
cold sonnet
#

😄

novel prairie
#

yea

paper sluice
novel prairie
#

yes

#

i already did this is a command i want to add to the bot im creating

slate swan
#

they have ubuntu installed

paper sluice
#

oh lol

paper sluice
slate swan
#

thats github codespaces and yes online vsc

slate swan
paper sluice
novel prairie
#

i didnt steal it it was online code for free

#

but anyway

#

ok

slate swan
#

most of the code available online rn are outdated

odd mango
#

sarth

slate swan
#

especially googling "discord.py music bot" and stuff

#

hi savvy

odd mango
#

what was i supposed to do here again

paper sluice
odd mango
#

python -m pip install -U git+https://github.com/Rapptz/discord-ext-menus?

slate swan
#

yes

#

poetry add git+https://github.com/Rapptz/discord-ext-menus

slate swan
#

or, open your repo,
press . on the keyboard
it will open a normal vsc editor
you can open it in codespace from there

paper sluice
slate swan
#

you got github students plan?

paper sluice
shrewd apex
#

i have mine but it's against tos

shrewd apex
slate swan
shrewd apex
#

unless u paidpithink for it

paper sluice
slate swan
#

thats weird can i see a ss

paper sluice
slate swan
novel prairie
novel prairie
#

?

#

yea wait

#

@bot.command()
async def kick(ctx, user: discord.Member, *, reason=None):
if user is None:
return await ctx.message.reply("You have to mention a user to do this!")
await member.kick(reason=reason)
await ctx.send(f'User {user.mention} has kicked.')

robust fulcrum
#

Guys how can we check that a user have mentioned someone in the message?

neat field
unkempt canyonBOT
#

A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.

Warning

The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.

paper sluice
novel prairie
#

File "main.py", line 257
await user.kick(reason=reason)
^
IndentationError: unindent does not match any outer indentation level

robust fulcrum
novel prairie
#

@bot.command()
async def kick(ctx, user: discord.Member, *, reason=None):
if user is None:
return await ctx.message.reply("You have to mention a user to do this!")
await user.kick(reason=reason)
await ctx.send(f'User {user.mention} has kicked.')

slate swan
#

Remove 1 space

neat field
#

what is your listener event function ?

novel prairie
#

oh nvm i fixed it

neat field
#

your on_message function

novel prairie
#

um

#

discord.ext.commands.errors.MissingRequiredArgument: user is a required argument that is missing.

robust fulcrum
#

Can you give me one example?

neat field
#

sorry wrong ping

novel prairie
#

i fixed it but it doesnt work for bots

#

like if i want to kick a bot it doesnt work

#

yes

#

it says this

#

discord.ext.commands.errors.MemberNotFound: Member "<@&998564457317928994>" not found.

#

no im mentioning the bot

wispy sequoia
#

is there any way to make the bot stop responding to the commands?

#

stop them

#

no replies at all

#

the bot is online but does not reply completely

#

yeah I already do

#

but I want it to stop replying on a certain status

#

like

#

if it's dnd it'll not reply

slate swan
#
bot.on_message= lambda m: ...
``` add this whenever you want that to happen
wispy sequoia
slate swan
#

how do you set the dnd status

wispy sequoia
cold sonnet
#

one day I'm going to calculate how many electrons this guy wastes with typing self.bot.user.id instead of the bot's actual id in his code

wispy sequoia
#

sniff

slate swan
slate swan
robust fulcrum
#

@slate swan

robust fulcrum
slate swan
#

ping one more person randomly ask them

cold sonnet
#

me

slate swan
#

lemon

#

(:

robust fulcrum
cold sonnet
#
if message.mentions:
    that person just pinged someone bro
#

!d discord.Member.mentioned_in

unkempt canyonBOT
slate swan
# wispy sequoia ye

you can do this ```py
bot = commands.Bot(...)

@bot.event
async def on_message(m: discord.Message) -> None:
if m.guild.me.status == discord.Status.dnd:
return
await bot.process_commands(m)

cold sonnet
#
if member.mentioned_in(message):
    member was pinged in that message omg
robust fulcrum
#

How will I get id of mentioned user?

cold sonnet
#

id?

#

message.mentions[0].id

robust fulcrum
#

I need it for my afk comamnd

slate swan
robust fulcrum
slate swan
cold sonnet
#

damnit

robust fulcrum
#

Hmmm

cold sonnet
robust fulcrum
#

Memebe = message.author?

slate swan
#

also, use a listener lol

#

event = bad

cold sonnet
#

e = b

robust fulcrum
slate swan
#

its the same, but .event replaced with .listen()

#
@bot.listen("on_message")
async def my_uwu_on_message(message: discord.Message) -> None:
  if message.author == client.user or not message.mentions:
    return```
robust fulcrum
#

Whats this the image

wispy sequoia
slate swan
#

why am I hallucinating

robust fulcrum
#

Who's this guy

slate swan
#

ur in a cog so u dont needa process it

slate swan
#

no

slate swan
slate swan
slate swan
#

<@&831776746206265384> some person is posting random pictures in the channel catcry

#

that human -> @echo latch
proof

wispy sequoia
velvet compass
#

@echo latch please respect channel topics and avoid spamming channels. Thanks

robust fulcrum
#

Sending weird gifs

#

Bruh

slate swan
#

swear down putting it in a cog will double the message @wispy sequoia

slate swan
velvet compass
#

!mute 749274869824487465 Ignoring staff instructions

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied mute to @echo latch until <t:1658152140:f> (59 minutes and 59 seconds).

novel prairie
#

how can i fix this?

wispy sequoia
slate swan
robust fulcrum
slate swan
#

...

novel prairie
#

um how can i fix this

novel prairie
#

.

slate swan
wispy sequoia
slate swan
#

which can be done only with events

wispy sequoia
#

thx then, it works

slate swan
#
async def on_message(message)
     member = #ur member
     if member.mentioned_in(message):
        print("pomg")
robust fulcrum
#

Ty

novel prairie
#

can someone help me with this

slate swan
#

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

!resources

unkempt canyonBOT
#
Resources

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

slate swan
#

:)

slate swan
slate swan
#

then check the id

wispy sequoia
slate swan
slate swan
slate swan
wispy sequoia
slate swan
#

Ash is writing an essay pepe_blush

#

Yeah on indents prob

#

expected, totally expected.

slate swan
robust fulcrum
slate swan
slate swan
slate swan
#

id' just ```py
if bot.user in message.mentions:
message.reply("touch grass")

#

absolutely

slate swan
robust fulcrum
#

Perrespective api bad

slate swan
#

how so

slate swan
slate swan
#

exit()

#

exit is useless most of the times, sys.exit better

slate swan
#

what makes you think that, and no

slate swan
slate swan
#

sparky jealous

#

i got the image on pinterest

#

absolutely not

slate swan
#

loooli im matching with a friend

slate swan
#

anime pfps are boring so

#

see my pfp

#

#NoAnimePfpGang

#

ew

#

be ready to get cancelled

slate swan
#

I guess it's time to move on from anime pfps

#

😔

slate swan
#

No await

#

All useless 💀

slate swan
#

no await needed

#

ew who likes that

#

Ash u were busy

wispy sequoia
slate swan
wispy sequoia
#

Pillow

slate swan
#

api

slate swan
#

messafe

#

cool down

#

!d discord.ext.commands.cooldown

unkempt canyonBOT
#

@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.

A command can only have a single cooldown.
sacred bluff
#

Hey hello, i need help with this .py script which utilizes the nextcord lib

from nextcord.ext import commands

bot = commands.Bot(command_prefix = '!')

@bot.command(name="hi")
async def SendMessage(ctx):
    await ctx.send('Hello!')

@bot.event
async def on_ready():
    print(f'\n\nSuccessfully logged in as: {bot.user.name} - {bot.user.id}')

if __name__ == '__main__':
    bot.run("TOKEN")```


i am not getting any errors but the command jus wont work, and yes the TOKEN in bot.run("TOKEN") is replaced to the bot's token. I also trued the help channels but redirected me here
slate swan
#

Nextcord

wispy sequoia
#

user based
@commands.cooldown(1, 90, commands.BucketType.user)
1 is the times the command can get used before the cooldown
90 is the seconds of cooldown

slate swan
#

👍

wispy sequoia
#

2.0

wispy sequoia
slate swan
#

Lol

wispy sequoia
#

update

#

this is what it should looks like

slate swan
#

description is optional

#

because what you are doing is running an infinite loop which blocks the rest of your code

vocal snow
#

Not making a message spammer would be a good fix

slate swan
#

idk create a task maybe ASakashrug

#

zeffo's advice too

lyric apex
slate swan
#

brad NM_PeepoBlushHat

velvet compass
#

Yo

slate swan
#

I even wrote down some non-blocking loop in this channel, needa check

#

why it isn't working, i installed this

slate swan
unkempt canyonBOT
#

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

slate swan
velvet compass
vocal snow
#

Poor Ashley :(

jolly rock
slate swan
#

3.10.1

jolly rock
#

I had trouble with a module cuz it was installed but for a diff python version

slate swan
slate swan
jolly rock
#

And ur code is in 3.10.1?

vocal snow
novel prairie
#

@bot.command()
@commands.is_owner()
@commands.has_permissions(ban_users = True)
async def ban(ctx, user : discord.Member=None, *, reason = None):
if user is None:
return await ctx.message.reply("You have to mention a user to do this!")
embed=discord.Embed (description=f"User {user.mention} is banned", color=discord.Color.red())
message = await ctx.message.reply(embed=embed)
await user.ban(reason = reason)

#

Version 7.5.0 of praw is outdated. Version 7.6.0 was released Tuesday May 10, 2022.
Traceback (most recent call last):
File "main.py", line 260, in <module>
@commands.has_permissions(ban_users = True)
File "/home/runner/zrl-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1779, in has_permissions
raise TypeError('Invalid permission(s): %s' % (', '.join(invalid)))
TypeError: Invalid permission(s): ban_users

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.

slate swan
#

ban_members instead of ban_users smh

jolly rock
#

Do what Ashley said and replace the ban_users

slate swan
jolly rock
#

Try restarting vscode

novel prairie
#

can someone sent the code fixed?

slate swan
jolly rock
#

@novel prairie in ur code replace ban_users with ban_members

#

ban_users is invalid

slate swan
#

the same problem

jolly rock
#

That permission doesn’t exist

slate swan
slate swan
#

NITRO Flex

slate swan
#

but i was installed ths

jolly rock
slate swan
#

pip install humanfriendly

#

Wth is humanfriendly

jolly rock
#

It’s a library

slate swan
#

!pip humanfriendly

unkempt canyonBOT
jolly rock
#

Ooh

#

Anyway @slate swan how’s it going

slate swan
#

good night av_pepeexit

slate swan
jolly rock
#

Ye

slate swan
jolly rock
#

Wait do what I said above

slate swan
#

dont use pip directly.

slate swan
#

its directing to your 3.9

jolly rock
#

Ye

slate swan
#

ash is pretty much of nightmare herself

vocal snow
#

Very true

jolly rock
#

Hrm

slate swan
jolly rock
#

I’m trying to remember how it did this

#

Cuz I dealt with something similar

slate swan
#

python3.10 / py3.10

jolly rock
#

Ye

#

Strixx remove the .1

#

And run

#

If it still says library not found then u need to install for correct python version

slate swan
slate swan
jolly rock
#

Okie strixx do
py -3.10 -m pip install humanfriendly

slate swan
#

Jk

#

Now no ot thanks

#

yeah work look at this now:

#

!d discord.Member.timeout

unkempt canyonBOT
#

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

Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").

You must have the [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") permission to use this.

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
slate swan
#

"New in 2.0"

#

You are using old version

#

how to upgrade

#

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

#

For this u need git installed

novel prairie
#

@bot.command()
@commands.is_owner()
@commands.has_permissions(administrator = True)
async def unban(ctx, user : discord.Member=None, *, member ):
if user is None:
return await ctx.message.reply("You have to mention a user to do this!")
embed=discord.Embed (description=f"User {user.mention} is unbanned", color=discord.Color.red())
message = await ctx.message.reply(embed=embed)
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split("#")

for ban_entry in banned_users:
    user = ban_entry.user

    if (user.name, user.discriminator) == (member_name, member_discriminator):
        await ctx.guild.unban(user)
        await ctx.send(f'Unbanned {user.mention}')
        return
#

discord.ext.commands.errors.MemberNotFound: Member "@velvet loom" not found.

#

how do i fix this

slate swan
#

u already have a member object just do user.unban()

vocal plover
#

but you're never going to have a member object when unbanning

#

if theyre banned they're not a member

#

it doesnt work because with the Member typehint the library searches for a member and doesn't find one

#

instead you'll want to use User

slate swan
#

user then?

#

Yeah

#

I mean that only 😔

#

My bad

novel prairie
#

@vocal plover

vocal plover
novel prairie
#

discord.ext.commands.errors.MissingRequiredArgument: member is a required argument that is missing.

slate swan
#

show code

novel prairie
#

@bot.command()
@commands.is_owner()
@commands.has_permissions(administrator = True)
async def unban(ctx, user : discord.User=None, *, member ):
if user is None:
return await ctx.message.reply("You have to mention a user to do this!")
embed=discord.Embed (description=f"User {user.mention} is unbanned", color=discord.Color.red())
message = await ctx.message.reply(embed=embed)
banned_users = await ctx.guild.bans()
user_name, user_discriminator = user.split("#")

for ban_entry in banned_users:
    user = ban_entry.user

    if (user.name, user.discriminator) == (user_name, user_discriminator):
        await ctx.guild.unban(user)
        await ctx.send(f'Unbanned {user.mention}')
        return
slate swan
#

why do you have an extra member argument.

#

....?

#

also, lucas unban oof

novel prairie
slate swan
#

you shouldn't be using that method for unbanning

#

Is your unban command looking like this?

    for ban_entry in banned_users:
         user = ban_entry.banned_users

         if (user.name, user.discriminator) == (member_name, member_discriminator):
             ...

Lucas' unban only works for banning people via their name#discrim, now, this way is not wrong, but there are easier ways of unbanning people, e.g.:

# Unbanning by ID only (converting the ID to a object using discord.Object):
await ctx.guild.unban(discord.Object(id = id))

# converting the given user to a User object by type hinting:
async def unbean(ctx, user : discord.User, reason = None): 
novel prairie
slate swan
#

nice.

jolly rock
#

Okie

#

Ye u can use id rather than loop through bans to find the user

#

Use what sarth did

novel prairie
#

bruh

#

i removed the unban command

#

and now it something like your ip: and idk df goin on

#

lmao

jolly rock
#

Huh

#

Send ss

novel prairie
#

it wont let me run the program

slate swan
#

type kill 1 in the shell and rerun the code.

novel prairie
#

ok

#

it worked thanks

drifting goblet
#

i need help my discord.py bot is not responding my command. what should i do =((((

slate swan
#

show code

robust fulcrum
#

Guys why we should not host bot at heroku?

slate swan
drifting goblet
slate swan
#

this gives no idea of what the issue can be, the piece of code you provided is correct.

robust fulcrum
#

Any free thing owo

drifting goblet
# slate swan this gives no idea of what the issue can be, the piece of code you provided is c...

import random
import time
from discord import Game
from discord.ext.commands import Bot

BOT_PREFIX = "."
TOKEN = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

client = Bot(command_prefix=BOT_PREFIX)

@client.command(pass_context=True)
async def ping(context):
await client.say("🏓Pong!")

@client.command(pass_context=True)
async def pong(context):
await client.say("🏓Ping!")

@client.command(name="8ball",
description="Answers a yes/no question.",
brief="Answers questions",
aliases=("eight_ball", "eightball", "8-ball"),
pass_context=True)
async def eight_ball(context):
possible_responses = [
"Sure, why not",
"Probably not",
"For sure",
"Never in a million years",
"The chances are pretty high",
]
await client.say(random.choice(possible_responses) + ", " + context.message.author.mention)

#

sry for my delay

robust fulcrum
#

Any free thing owo

slate swan
#

12 months of aws for free ASakashrug (basic)

#

or oracle's av_pepeexit

#

or subscribe to the github student developer pack, youll get a year's subscription for digital ocean

hybrid fjord
#

???? using rapptz git thing

tawdry perch
#

Don't they require CC?

slate swan
#

yes

slate swan
#

!d discord.Client.run

unkempt canyonBOT
#

run(token, *, reconnect=True, log_handler=..., log_formatter=..., log_level=...)```
A blocking call that abstracts away the event loop initialisation from you.

If you want more control over the event loop then this function should not be used. Use [`start()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.start "discord.Client.start") coroutine or [`connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.connect "discord.Client.connect") + [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login").

This function also sets up the logging library to make it easier for beginners to know what is going on with the library. For more advanced users, this can be disabled by passing `None` to the `log_handler` parameter.

Warning

This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.
hybrid fjord
slate swan
#

you can set the log_handler to None to remote it easy

hybrid fjord
#

any ideas? ive enabled application.commands during invitation

slate swan
hybrid fjord
#

no idea honestly. following a tutorial

odd mango
#

can i make help command categories manually using command names?

slate swan
hybrid fjord
#

alright

slate swan
#

no wait

#

dont use on_ready

#

oh wait

hybrid fjord
#

any alternative? or should i just remove it as a whole

slate swan
#

the indentation level

hybrid fjord
slate swan
#

the on_ready functionis inside the init function

hybrid fjord
#

ahh

slate swan
#

nvm

hybrid fjord
#

no you're right

slate swan
#

lemme self advertise my gist pepeShy gib me a minute

hybrid fjord
#

yeah it works lol

#

no you got it. faulty indentation level

#

now i have a few other questions related to this

slate swan
hybrid fjord
#

i've made lots of bots in the non-2.0 version so i'm familiar with stuff like create_channel and add_reaction etc.
are they any different in this version?

#

this is my first time on the new discord.py version so i'm not too sure

slate swan
#

no

hybrid fjord
#

okay perfect. appreciate your help 🙌

slate swan
#

and

hybrid fjord
#

will do

#

so just replace on_ready with setup_hook or is it a whole other block of code?

drifting goblet
#

why @client.command() is not working guy :((((

hybrid fjord
#

no for?

slate swan
#

well you do it like this (same) but on_ready and setup_hook are different

hybrid fjord
#

ah

slate swan
hybrid fjord
#

👍

faint sapphire
#

its possible to make a bot take a screenshot of a message?

slate swan
#

no

faint sapphire
#

im tryna make it take a screenshot of a discord server invite

#

i thought i saw it done once

slate swan
#

If I use PIL screenshot thing and make a ss comandn will it take a screenshot of my screen?

slate swan
slate swan
slate swan
haughty nova
drifting goblet
faint sapphire
#

anyone knows how a discord bot could verify the number of members a server has if it takes a server invite as an argument

slate swan
# slate swan 12 months of aws for free <:ASakashrug:580791198483087370> (basic)

Would not recommend a Enterprise hosting provider for a Discord bot. I have seen way to many new people run up bills from a few dollar to 100s, because they dont know what they are doing, leaving services they dont need running, etc.

Better off with a RasberryPi or something and just host from that, if you want free.

hybrid fjord
#

how do i create a thread with dpy2?

idle radish
#

I'm unable to send price data
ERROR: [1/1] Webhook status code 400: {"embeds": ["0"]}
i tried different datatypes: str, float, int none of them works. When i hard code input the price it is working.

In my dict it looks like this: 'price': 169.99,

Using this piece of code:

embed.add_embed_field(name="price", value=item['price'])

Any ideas what im doing wrong?

slate swan
#

!d discord.Guild

unkempt canyonBOT
#

class discord.Guild```
Represents a Discord guild.

This is referred to as a “server” in the official Discord UI.

x == y Checks if two guilds are equal.

x != y Checks if two guilds are not equal.

hash(x) Returns the guild’s hash.

str(x) Returns the guild’s name.
slate swan
#

discord.guild is a module and must exist, they havent installed discord.py properly mb

#

discord.guild is a module? awkward

#

oh a file

#

skill issue

#

Lol

noble minnow
#

Hi, excuse me for disturbing you. I'm new and I would like to know if someone could teach me or inform me on the bases of the code of a discord bot.

#

I use Visual Studio Code

warped mirage
#

guys i need help , 1) py @client.tree.command(description="Unban a username") @app_commands.checks.has_permissions(ban_members = True) async def unban(inter: discord.Interaction, id: discord.User): try: await inter.response.send_message(f"{id.name} has been unbanned") except: await inter.reply(f"The user you are trying to unban is not banned") finally: await inter.guild.unban(discord.utils.get(await inter.guild.bans(), id=id)) i need this cmd to be multi guild, 2) it doesnt unban the user but says it did

torn sail
#

Put the unban inside the try

hybrid fjord
#

how to create a thread with dpy 2.0?

warped mirage
torn sail
#

!d discord.TextChannel.create_thread

unkempt canyonBOT
#

await create_thread(*, name, message=None, auto_archive_duration=..., type=None, reason=None, invitable=True, slowmode_delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a thread in this text channel.

To create a public thread, you must have [`create_public_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_public_threads "discord.Permissions.create_public_threads"). For a private thread, [`create_private_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_private_threads "discord.Permissions.create_private_threads") is needed instead.

New in version 2.0.
hybrid fjord
#

thanks

torn sail
#

@hybrid fjord

warped mirage
#
@client.tree.command(description="Unban a username")
@app_commands.checks.has_permissions(ban_members = True)
async def unban(inter: discord.Interaction, id: discord.User):
    try:
        await inter.response.send_message(f"{id.name} has been unbanned")
        await inter.guild.unban(discord.utils.get(await inter.guild.bans(), id=id))
    except:
        await inter.reply(f"The user you are trying to unban is not banned")``` like this/ also will it work for multi guild
hybrid fjord
#

also, with slash commands, how do i make the slash command executor hidden

torn sail
torn sail
hybrid fjord
#

discord.app_commands.errors.CommandInvokeError: Command 'ask' raised an exception: NameError: name 'create_thread' is not defined

torn sail
#

Show code

hybrid fjord
#

oh hold on

#

discord.app_commands.errors.CommandInvokeError: Command 'ask' raised an exception: HTTPException: 400 Bad Request (error code: 20035): Guild premium subscription level too low

i know what the error means, but what's the lowest auto-archive without boost

torn sail
#

Not sure

hybrid fjord
#

discord.app_commands.errors.CommandInvokeError: Command 'ask' raised an exception: HTTPException: 400 Bad Request (error code: 20035): Guild premium subscription level too low

says 24h is too low, but i can make a 24h thread in the same guild??

#

ah, u cant create a thread w/o a message without boost

torn sail
# warped mirage wdym?
try:
    await guild.unban(...)
except discord.HTTPException:
    await send('failed')
else:
    await send('success')
warped mirage
# torn sail ```py try: await guild.unban(...) except discord.HTTPException: await se...
@client.tree.command(description="Unban a username")
@app_commands.checks.has_permissions(ban_members = True)
async def unban(inter: discord.Interaction, id: discord.User):
    try:
        await inter.guild.unban(discord.utils.get(await inter.guild.bans(), id=id))
    except discord.HTTPException:
        await inter.response.send_message('Unbanning Failed')
    else:
        await inter.response.send_message('Unbanning Has been Successful')``` like this?
torn sail
loud gulch
#

My discord bot is sending 2 embed messages. Here is the code (Im working on it) @client.command() async def embed(ctx): embed=discord.Embed(title="Embed Message", description="Test Message", color=discord.Color.blue()) await ctx.send(embed=embed)

slim heart
#

i thought i won't

warped mirage
#

Idk I think with the id it’s Easier

torn sail
warped mirage
#

oh

warped mirage
# torn sail alright but pass `id` straight onto `unban`
@client.tree.command(description="Unban a username")
@app_commands.checks.has_permissions(ban_members = True)
async def unban(inter: discord.Interaction, user: discord.User):
    try:
        await inter.guild.unban(discord.utils.get(await inter.guild.bans(), id=user))
    except discord.HTTPException:
        await inter.response.send_message('Unbanning Failed')
    else:
        await inter.response.send_message('Unbanning Has been Successful')``` will this work?
torn sail
warped mirage
#

can u help me fix it? cuz i have this: await inter.guild.unban(discord.utils.get(await inter.guild.bans(), id=user))

torn sail
#

await inter.guild.unban(user)

warped mirage
#

will this work for multiguild btw?

torn sail
#

yeah

warped mirage
#

ok]

torn sail
#

wait wdym by multiguild

warped mirage
#

im making a public bot, it will work in any server the command is ran in

torn sail
#

yeah ok

slate swan
#

why it isn't work?

warped mirage
# torn sail yeah ok

it doesnt work now, because if its user: then it wont work, the user isnt in the server so i cant mention it

warm tulip
#

hello

slate swan
warped mirage
#

has to be done through id

warm tulip
slate swan
torn sail
warm tulip
warped mirage
torn sail
#

you can name it whatever you want

slate swan
warm tulip
stiff fern
warm tulip
#

ok

#

@slate swan pip : The term 'pip' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was
included, verify that the path is correct and try again.
At line:1 char:1

#

:/

#

wat to do @slate swan

wanton cipher
#

you need to fix your pip

stiff fern
#

Anyone know how I could fix this

#

Or what the issue is

wanton cipher
#

or install python xD

warm tulip
#

how to fix pip

slate swan
#

try python -m pip install....

warm tulip
#

python -m pip install....

slate swan
#

!dashmpip

unkempt canyonBOT
#
Install packages with `python -m pip`

When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.

Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.

Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.

warm tulip
#

with those ......... ?

sour basalt
#
@spin.error
async def spin_error(ctx, error):
if isinstance(error, discord.MissingPermissions):
        embed = discord.Embed(
            title="TelSpin Role Error",
            description=f"you have alredy the role",
            colour=0xF42222,
        )
        await ctx.send(embed=embed)
    else:
         raise error

not get anything if my meber as alredy the role

slate swan
#

it invokes pip as a module

slate swan
warm tulip
#

it have a eror with python -m pip install your_package

#

python : The term 'python' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path
was included, verify that the path is correct and try again.
At line:1 char:1

  • python -m pip install https://github.com/Rapptz/discord.py
  •   + CategoryInfo          : ObjectNotFound: (python:String) [], CommandNotFoundException
      + FullyQualifiedErrorId : CommandNotFoundException
sick birch
#

You need to install python

slate swan
#

try, py

sick birch
#

Or that

warm tulip
#

im using python

#

pycharm*

slate swan
#

use the name py over python

sick birch
#

Sorry I just never used python on a windows machine

quaint epoch
#

if you have python installed you might need to add it to your path

warm tulip
warm tulip
#
Collecting https://github.com/Rapptz/discord.py
  Downloading https://github.com/Rapptz/discord.py
     / 207.1 kB 342.9 kB/s 0:00:00
  ERROR: Cannot unpack file C:\Users\Copy Service\AppData\Local\Temp\pip-unpack-iylvvlmk\discord.py (downloaded from C:\Users\Copy Service\AppData\Local\Temp\pip-r
eq-build-iybwcn23, content-type: text/html; charset=utf-8); cannot detect archive format
ERROR: Cannot determine archive format of C:\Users\Copy Service\AppData\Local\Temp\pip-req-build-iybwcn23
WARNING: You are using pip version 22.0.4; however, version 22.1.2 is available.
You should consider upgrading via the 'C:\Users\Copy Service\AppData\Local\Programs\Python\Python310\python.exe -m pip install --upgrade pip' command.
PS C:\Users\Copy Service\PycharmProjects\bot>
```Done?
stiff fern
slate swan
#

seems to me like it had an error

stiff fern
#

anyone?

cold tide
#

Were can i find someone who codes in json to help w holding data for my discord bot??

sour basalt
#
@spin.error
async def spin_error(ctx, error):
if isinstance(error, discord.MissingPermissions):
        embed = discord.Embed(
            title="TelSpin Role Error",
            description=f"you have alredy the role",
            colour=0xF42222,
        )
        await ctx.send(embed=embed)
    else:
         raise error

not get anything if my meber as alredy the role

sick birch
cold tide
sick birch
jagged estuary
#

@stiff fern

stiff fern
#

whats wrong with it 😫

jagged estuary
#

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

jagged estuary
stiff fern
#

i will try 🥲

#

It says invalid requirement :C which I dont know what its specifically referring to but it did run so I thank you for that 😅

#

How its saying self has no load extension method

#

even tho self is the bot?

sage otter
#

Swap discord.Client to commands.Bot

stiff fern
#

ty <3

cold sonnet
#

that's a change presence on_ready

stiff fern
cold sonnet
#

not good don't like

#

because you can set the activity and status in commands.Bot()

stiff fern
#

how would I do that if you dont mind

#

Like inside the actual () just write it in?

vale wing
#

You can set the activity when connecting to webhook iirc

#

!d discord.ext.commands.Bot constructor kwarg

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/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.

Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.

async with x Asynchronously initialises the bot and automatically cleans up.

New in version 2.0.
cold sonnet
#

Don't change_presence (or make API calls) in on_ready within your Bot or Client.
Discord has a high chance to completely disconnect you during the READY or GUILD_CREATE events (1006 close code) and there is nothing you can do to prevent it.

Instead set the activity and status kwargs in the constructor of these Classes.

bot = commands.Bot(command_prefix="!", activity=..., status=...)

As noted in the docs, on_ready is also triggered multiple times, not just once.

Basically: don't 👏 do 👏 shit 👏 in 👏 on_ready.

stiff fern
#
class aclient(commands.Bot(
        activity=discord.Activity(
        type=discord.ActivityType.watching,
        name="the Nebula Network"))):
#

tada

#

Any other improvements to make?

vale wing
#

You can't inherit from an object

#

Can't make improvement to what won't work

#

You need to parse these parameters to superclass init

stiff fern
vale wing
#

I mean OOP class inheritance

#

You can inherit from a class which is commands.Bot, not from an actual instance of that class, you init super class with super().__init__(...)

pliant gulch
vale wing
#

Class inherits from object ik that but let's not dive into useless for this case stuff

#

For this case he should not inherit from an instance

pliant gulch
#

!e ```py
class A:
def init(self, *meta: tuple[str, tuple[type, ...], dict[str, "Any"]]):
...

class B(A()):
...

unkempt canyonBOT
#

@pliant gulch :warning: Your eval job has completed with return code 0.

[No output]
hybrid fjord
#

how do i add options to slash commands such as "yes"/"no" d.py 2.0?

vale wing
#

Idk if dpy 2.0 supports enum typehinting but I think that should do the thing

stiff fern
#

I dont think so

vale wing
#

Ok I am not into like explaining OOP (I suggest reading about it nevertheless)

class AClient(commands.Bot):  # and yeah the naming convention
    def __init__(self):
        super().__init__(command_prefix=".", intents=discord.Intents.all())  # why'd you even provide application_id```
stiff fern
#

Idk I just thought you needed the application_id in there lol

sick birch
stiff fern
#

I thought thats what I had

#

oh nvm I see what ur saying

#

ty guys <3

vale wing
#

@sick birch btw I made that guide about docker

#

Would you like to look at it

sick birch
#

Awesome, thanks for your work. Could you PR that to python-discord/site and I can review it for you?

#

Just follow the template that other similar PRs have done (e.g Okimii's, Ashley's)

vale wing
#

Ok I think ima figure it out

sick birch
#

Feel free to ask me if you have any troubles, I'd be more than happy to get it sorted out

vale wing
#

All checks failed ig I've done something wrong tho

slate swan
#

I want to make a command that after some time, it would change the message automatically.
Example: .text and it would say "good morning". After a few hours, if I re-executed the command, it would say "good night".
Does anyone have a base for that?

sick birch
vale wing
#

Ok

sick birch
slate swan
slate swan
sick birch
vale wing
#

@sick birch ok those 2 checks are successful now

sick birch
#

Awesome. The rest are broken for now so don't worry about them. I will review it when I've got time, and thanks again!

vale wing
#

Ty

gusty shard
#
@tasks.loop(seconds=40) 
async def changepresence():
    global x
    guild = client.get_guild(957301746739339307)
    game = iter(
        [
            "Help hâlâ hazır değil 😐",
            f"Kasada {data['kasa']['cash']} lira var!",
            f"Casino {guild.members} kişi!",
            "💸",
            f"Sürüm: {version}",
            "Özel roller, para ve boost almak için !Bağış yazabilirsin.",
        ]
    )
    for x in range(random.randint(1, 6)):
        x = next(game)
    await bot.change_presence(activity=discord.Game(name=x))```
#

can somebody help me please?

#

its not working

wise gull
#

hello how to ping users with bot

i mean to use command like !ping <user>
and bot will ping him 10times

slate swan
stiff fern
wise gull
#

but how to mention someone

tidal hawk
#

await ctx.send(user.mention())
perhaps

#

make sure that the user is a member object

slate swan
# stiff fern sub sub sub classing?

yeah~
commands.Bot is a subclass of discord.Client (sub-
you construct a new Bot using commands.Bot (sub-
and the subclass it again as aclient (subclassing

which could have done easily with methods you were just told

stiff fern
#
from email.mime import application
from wsgiref.util import application_uri
import discord

from discord.ext import commands
from discord import app_commands


class aclient(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix='.', 
            intents=discord.Intents.all(),
            activity=discord.Activity(
                type=discord.ActivityType.watching,
                name="Testing Functionality"))
        self.synced = False

    async def on_ready(self):
        await self.wait_until_ready()
        if not self.synced:
            await self.tree.sync()
            self.synced = True
        
        print(f'{self.user} has initialized.')
        
    async def setup_hook(self):

        print('Setup_hook fired')

        self.initial_extensions = [
            'cogs.core',

            'cogs.suggestion',
            'cogs.invite',
            'cogs.group',
            'cogs.ping',]

        for ext in self.initial_extensions:
            await self.load_extension(ext)

            print(f'{ext} loaded')


client = aclient()
#bot.run(os.environ["DISCORD_TOKEN"])
tree = app_commands.CommandTree(client)
#

Is what is have rn if u want to nitpick it so I can try figuring some of this stuff out because to me it looks normal but to everyone else theyre like wtf 😂

sick birch
#

I think there's really no point to the whole self.synced part, and you can just remove your on_ready altogether and sync inside the setup_hook

slate swan
#

this is actually normal

#
client = aclient()
#bot.run(os.environ["DISCORD_TOKEN"])
tree = app_commands.CommandTree(client)
``` and this is not needed, `discord.ext.commands.Bot` already has a tree linked to it
sick birch
#

And you can also define your tree inside your class's constructor, so you can access tree where you can access client using client.tree

slate swan
#

!d discord.ext.commands.Bot.tree

unkempt canyonBOT
#

property tree```
The command tree responsible for handling the application commands in this bot.

New in version 2.0.
stiff fern
#

thank u for the suggestions!

left idol
#

so i have a command that doesn't work unless its in a specific channel that has a 1m cooldown. can i make it so if they are in the wrong channel it doesn't trigger cooldown?

torn sail
#
def cooldown_for_channel(message):
    if message.channel.id != 28482304823048:
        return None
    return commands.Cooldown(1,1)

@commands.dynamic_cooldown(cooldown_for_channel)
@bot.command()
async def cmd(ctx):
    await ctx.send("test")
left idol
slate swan
#

does anyone know why my code isnt working? Im trying to make it say "Goodbye (mention person who sent the command)" @bot.command() async def goodbye(ctx): await ctx.reply("Goodbye {message.author.mention} 👋!")

slate swan
slate swan
#

ah i'll try it it out

slate swan
# slate swan ctx. author.mention

it didnt seem to work. here is the new code: @bot.command() async def goodbye(ctx): await ctx.reply("Goodbye {ctx.author.mention} 👋!")

#

define 'not work' what's the issue

#

well when i run my goodbye command it says "Goodbye {ctx.author.mention}"

#

You forgot the f before the string

slate swan
hardy yoke
stiff fern
#

Well I didnt reply to the right thing but would this working for syncing commands

#

since that message isnt really good context

drifting goblet
#

@client.command() still working?

stiff fern
#

Do you need to include the guild id or something for slash commands to work?

dull knot
#

This is embarrassing to ask but

@bot.command()
async def testing(ctx):
      embed = disnake.Embed(
        title="Learning Embeds", 
        description="Testing description"
      )
      await ctx.send(embed=embed)

It doesn't respond when I type !testing.
I've enabled intents from the Developer Portal

#

Plus I already wrote this piece of code

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

bot = commands.Bot(command_prefix='!', intents=intents)
#

And I already imported intents

#

Oh wait.. There's this that shows up. I mean, I've enabled all intents from the portal yet this just won't go away

slate swan
#

You need to enable message_content intents in the code too

dull knot
#

How do i do that?

#

Intents.message_content = True
??

#

Like this?

#

It says 'Intents' object has bo attribute

#

Oh. Wait nvm

#

Got it! Thx!!

drifting goblet
stiff fern
pliant gulch
stiff fern
#

Because my cogs are loading and everything appears to be running, I get no errors but whenever I try to start the command nothing shows up, like the bot doesn't appear in the list of options for slash commands

pliant gulch
stiff fern
#

applications.commands and bot are the only 2 you should need right

jaunty isle
#

Hey so I was building a discord bot for a community i am a part of and i recently heard that slash commands are being made compulsory for all bots.. Is it going to be easier to continue with discord.py and develop /commands or is it better to switch to hikari?

drifting goblet
sick birch
jaunty isle
sick birch
#

Never worked with Hikari, some of the other folks here have so you'd have to ask them

jaunty isle
#

I see.. thanks

stiff fern
stiff fern
#

Ill reinvite just in case

drifting goblet
pliant gulch
#

If you can't make a URL just use this https://discord.com/api/oauth2/authorize?client_id=(YOUR BOT ID)&permissions=0&scope=bot%20applications.commands

stiff fern
#

says its online but doesnt show up in the list

flat pier
#

are you syncing properly after changing/adding or removing any commands? (assuming you're using discord.py 2.0.0a)

#

though in any of the forks you need to sync as well i think

#

@stiff fern

stiff fern
#

I think i am? unless im not

flat pier
#

well it's not a good idea at all to auto sync, most people have commands to sync everything when it's needed

#

and i think you should be doing self.bot.tree.sync()

dull knot
#

What should i input here if I want the bot to place the user's avatar as the thumbnail?

embed.set_thumbnail(url=???)

I tried putting
{member.avatar_url} but it didn't work

flat pier
flat pier
stiff fern
flat pier
#

it says self.tree.sync() no?

#

that's what the ss reads

stiff fern
#

I see you did self.bot I just did self

flat pier
#

i'd suggest reading up on what self does, say you have self.bot = bot in your class, you'd have to use self.bot to get the bot object

flat pier
flat pier
dull knot
#

Alright, will read thst. Thx!

flat pier
#

Np goodluck

dull knot
#
#The codes preceding this one showed no errors regarding indentation. 

url="https://discord.com/channels/943462265317912576/953113946930438185/"
      )
  
   embed.set_thumbnail(url="{member.avatar.url}")

    await ctx.send(embed=embed)

Help. I couldn't figure it out myself. It said:

indentation error. Unindent doesn't match any outer indentation level
hardy yoke
dull knot
#

More or less

hardy yoke
#

none of that is on the same line

dull knot
#

I'm still fairly new so I'm still not very experienced with it.

hardy yoke
#

it should just be

url="etc etc"
embed=whatever
await ctx.....```

instead of
```py
url="etc"
     embed=
             await```
dull knot
#

Wait let me try

#

When that type of error is returned it could also mean that both spaces and tabs are being used unnecessarily on some lines, right?

hardy yoke
#

yes

dull knot
#

Let me try rechecking the whole code first

hardy yoke
#

you can't mix n match tabs/spaces

#

repl can also cause indentation issues randomly sometimes if you're using that

dull knot
#

Yeah. I'll probably be fixing it later lol. Gtg. Seems like it's only indentations that's the problem

#

I'll just double check everything

#

Thx for the help

#

Wait. Seems like I fixed it... But now another problem is that the repl is loading forever.

#

Whelp, I'll figure it out later

rain olive
#

self bots are against ToS lmao

#

then dont ask for it here...?

unkempt canyonBOT
#

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

limber bison
#

i want to read it\

sick birch
#

GitHub might be a better place to read it honestly

limber bison
#

in my pc

#

pip install thing ?

sick birch
#

That’s very dependent on your python installation location, and any activated virtual environments

#

I believe there’s a pip command to show you where the package is located, but personally I don’t use pip

limber bison
#

git hub add ?

sick birch
#

Poetry mostly

#

We use it for most of our projects here at pydis, so I kind of just got used to that and use poetry now lol

#
  • poetry is very cool
dry crown
#

how does bot replies in a specific server? because I have a problem with this. For example I have a Server 1 and Server 2
if I send command to Server 1 the bot replies in Server 2.

#

Can someone explain me?

sick birch
#

We’d need to look at your code to be sure though

dry crown
dry crown
limber bison
#
import okkk

okkk.okk()
class MyClient(discord.Client):
    async def on_ready(self):
        print('Logged on as', self.user)

    async def on_message(self, message):
        if message.author == self.user:
            return

        if message.content == 'ping':
            await message.channel.send('pong')

client = MyClient()
client.run('xxx')```
limber bison
# limber bison ```import discord import okkk okkk.okk() class MyClient(discord.Client): as...
import random
import asyncio

class okk(discord.Client):
       
      async def on_message(self, message):
        
        if message.content.startswith('guess'):
            await message.channel.send('Guess a number between 1 and 10.')

            def is_correct(m):
                return m.author == message.author and m.content.isdigit()

            answer = random.randint(1, 10)

            try:
                guess = await self.wait_for('message', check=is_correct, timeout=5.0)
            except asyncio.TimeoutError:
                return await message.channel.send('Sorry, you took too long it was {}.'.format(answer))

            if int(guess.content) == answer:
                await message.channel.send('You are right!')
            else:
                await message.channel.send('Oops. It is actually {}.'.format(answer))```
#

file one and 2 is it ok ?

#

@dry crown😳

dry crown
limber bison
#

i want guess command works .. file 2 line 7

dry crown
#

what error is given

limber bison
#

nothing

#

i think i didnt import in a right way

dry crown
#

from okkk import okk

limber bison
#

hmmm not working

dry crown
#

oh I see the problem

limber bison
dry crown
#

wait

#

can I change some of your code so it will work and I will explain it to you

limber bison
dry crown
#

ok ok wait

#

File 1

import discord
from okkk import okk

class MyClient(discord.Client):
    
     async def on_ready(self):
         print('Logged on as', self.user)
         self.okk = okk(self)

     async def on_message(self, message):
         await self.okk.__receive_message__(message)
         if message.author == self.user:
              return

         if message.content == 'ping':
              await message.channel.send('pong')

File 2

import discord
import random
import asyncio

class okk(discord.Client):
    def __init__(self, client):
        self.client = client
       
     async def __receive_message__(self, message):
          if message.content.startswith('guess'):
               await message.channel.send('Guess a number between 1 and 10.')
               def is_correct(m):
                    return m.author == message.author and m.content.isdigit()

               answer = random.randint(1, 10)
               try:

                   guess = await self.wait_for('message', check=is_correct, timeout=5.0)
               except asyncio.TimeoutError:
                   return await message.channel.send('Sorry, you took too long it was {}.'.format(answer))

          if int(guess.content) == answer:
               await message.channel.send('You are right!')
          else:
               await message.channel.send('Oops. It is actually {}.'.format(answer))
#

@limber bison

limber bison
#
unindent does not match any outer indentation level (okkk.py, line 9)
  File "C:\Users\Kamal kishore\Desktop\S3X\main.py", line 2, in <module>
    from okkk import okk```
dry crown
#

fix the indentations

limber bison
#

both files are in same location\

#

@dry crown

dry crown
#

yes but the problem is the indentation

limber bison
dry crown
#

align to the white line

limber bison
#

ohh got it

#

thanks @dry crown

#

@dry crown working , what mistake i am doing ? 🥲

#

from import ?

#

is one right

dry crown
#

is it working

dry crown
#

discord.utils.get I guess

haughty echo
#

URBAN API necessary?

limber bison
#

Can I get economy bot git so I can read it

placid skiff
#

!d discord.Client.guilds

unkempt canyonBOT
haughty echo
#
Replit: Updating package configuration

--> python3 -m poetry add aiohttp discord get
Ignoring invalid distribution -iohttp (/home/runner/Darknix-Security-Fixed/venv/lib/python3.8/site-packages)
Using version ^3.8.1 for aiohttp
Using version ^1.7.3 for discord

  ValueError

  Could not find a matching version of package get

  at venv/lib/python3.8/site-packages/poetry/console/commands/init.py:367 in _find_best_version_for_package
      363│         )
      364365if not package:
      366# TODO: find similar367raise ValueError(
      368"Could not find a matching version of package {}".format(name)
      369│             )
      370371return package.pretty_name, selector.find_recommended_require_version(package)
exit status 1
sour basalt
#
@spin.error
async def spin_error(ctx, error):
if isinstance(error, discord.MissingPermissions):
        embed = discord.Embed(
            title="TelSpin Role Error",
            description=f"you have alredy the role",
            colour=0xF42222,
        )
        await ctx.send(embed=embed)
    else:
         raise error

not get anything if my meber as alredy the role

hazy oxide
#

it's missing permissions

#

it tells the member if they don't have the required permissions

vale wing
#

.bm

vale wing
#

There's no package named get

livid hedge
#

I got this error trying to use Discord.py's components

"Value of field "type" must be one of (2, 3, 5, 6, 7, 8)."

view = discord.ui.View()
view.add_item(
    discord.ui.TextInput(label='Titolo', style=discord.TextStyle.short)
)
await ctx.send(view=view)
vale wing
#

You can add TextInput only to modals

livid hedge
#

discord.ui.Modal() ?

#

instead of discord.ui.View(), right?

#

or do I have to add the modal to a view?

vale wing
livid hedge
#

ty

#

it's a bit more complicated

vale wing
#

Not sure bot most likely input function causes blocking

livid hedge
#

can you precisely explain what you're trying to do?

vale wing
#

Why even make communication through terminal

#

You could redirect messages to your DMs for example

#

And then have sort of reply button

#

Or even simply reply to a message

#

You have 2 functions named the same

#

Also what the hell for do you need asyncio.run() there

vale wing
#

Lmao

livid hedge
#

I need a "command" function flow

vale wing
livid hedge
#
@bot.command()
async def sondaggio(ctx):
    modal = discord.ui.Modal(title="Sondaggio")
    modal.add_item(
        discord.ui.TextInput(label='Titolo', style=discord.TextStyle.short)
    ) 
    await ctx.send(view=modal)

like this, but I don't know how to use it

vale wing
#

This is the wrong way

#

Use subclassing

livid hedge
#

isn't it expensive?

vale wing
#

You could make own "generic" class depending on your needs

livid hedge
#

ok I got that this is the right way, but why?

#

but in the example the subclass is not generic, am I wrong?

vale wing
livid hedge
#

okay

#

another question about subclassing

#

do I have to subclass only when talking about components?

vale wing
livid hedge
vale wing
#

Personally I usually subclass commands.Bot

#

And we all subclass cogs

livid hedge
vale wing
livid hedge
#

mine is not enough to make the right questions lol

vale wing
#

@livid hedge just asking do you know about class inheritance

livid hedge
#

yes

vale wing
#

Subclassing is that thing

livid hedge
#

yeah yeah I know

vale wing
#

I think you should be able to figure out when to use it by yourself shouldn't you

livid hedge
#

okay

#

thank you, Exenifix

vale wing
livid hedge
#

gotta rewrite a lot of code

vale wing
#

Gl with that

livid hedge
#

it's gonna be a nice day

placid skiff
#

There are some of them more advanced, like CheckFailure when you want to create a custom check

vale wing
#

I am currently rewriting a bot that I made with sync sqlite wrapper (why the hell) now it just eats 100% of CPU every 20 seconds and is extremely slow

livid hedge
#

damn

placid skiff
#

Please bro my senior asked me to study a database, which is used to schedule things

#

names of tables and rows are like this XPRTR_CNFG

vale wing
#

The what

placid skiff
#

i mean WTF, why people create databases when they're drunk

vale wing
placid skiff
#

Lmao

sage niche
#

hey can someone help me and say how those „new“ buttons are called under messages which u click and get a message that only you can see?

vale wing
#

The messages are called ephemerals

#

The buttons are buttons

sage niche
#

tyy and what are those new apps that look like bots?
I couldn’t find anything in google when I searched for Apps?

vale wing
#

Bots are apps

sage niche
#

like this I mean what’s the difference

vale wing
#

These are discord integrations

#

They access some of your discord data to use on their site

#

You can create app on dev portal not only for bots

sage niche
#

oh do you know where I can learn about coding such?

vale wing
#

Afaik it uses discord API as well so you can just use their docs

livid hedge
#

where can I find a "doc" that correctly tells me how to subclass discord API?

vale wing
#

You can't subclass API

livid hedge
vale wing
#

Erm

livid hedge
#

im rewriting everything

vale wing
#

Subclassing is a way of extending the functionality of another class

livid hedge
#

I have to improve my english

livid hedge
#

but for example I want to subclass the Bot class

vale wing
#

What functionality are you going to add to it

livid hedge
#

I think doing it "manually" isn't the fastest way

#

for example the commands

#

I can add them inside or outside

vale wing
#

You group commands into cogs

livid hedge
#

I don't know which is the """cleaner""" way to do it

vale wing
#

If you follow the best practice

livid hedge
#

okay

#

so where can I find about cogs?

vale wing
#

I think there were some tutorials

livid hedge
#

yeah but

#

I followed a tutorial to create bots

#

and know I just discovered that I have to subclass

#

I have to search through docs

#

I think that's the best way to do it

placid skiff
#

Lol tutorials don't teach you how to code a bot

#

they teach you how to create a bot, it's pretty different

vale wing
#

This has a pretty nice explanation about cogs but for forks, you can find out the principle and then look at the docs because for dpy 2.0 it's a bit different

#

@livid hedge

#

Also you may check some projects on github like the one I linked to you before

livid hedge
#

okay, thanks

#

I am reading "disnake"

#

isn't it a third-party library?

livid hedge
vale wing
livid hedge
#

ok, ty

brittle river
slate swan
#

dynamic url?

#

wha...

brittle river
#

no link appear in embed

shrewd apex
brittle river
shrewd apex
#
msg = await ctx.send(embed=embed)
newembed = discord.Embed()
await msg.edit(embed=newembed)
brittle river
#

OOO ty!

slate swan
#

zeffo NM_peepoUwU

vocal snow
#
    @classmethod
    async def validate(cls, bot: Bot, iact: Interaction):
        if iact.guild is None:
            raise GuildOnlyException
        user = cast(Member, iact.user)
        voice_client = cast(Optional[Voice], iact.guild.voice_client)
        if (voice := user.voice) and (channel := voice.channel):
            if not voice_client:
                voice_client = await channel.connect(cls=Voice)
            elif channel != voice_client.channel:
                if len(voice_client.channel.members) == 1:
                    await voice_client.move_to(channel)
                else:
                    raise DifferentVoiceException
        else:
            raise NoVoiceException

        return cls(
            bot=bot,
            guild=iact.guild,
            voice_client=voice_client,
            user=user,
            channel=cast(GuildMessageable, iact.channel),
            interaction=iact,
        )
``` how i can shorten pls
slate swan
#

okay sorry for greeting

vocal snow
paper sluice
#

maybe

voice_client = cast(Optional[Voice], iact.guild.voice_client) or await channel.connect(cls=Voice)