#discord-bots

1 messages · Page 1152 of 1

unkempt canyonBOT
#

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

Edits the current profile of the client.

Note

To upload an avatar, a [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object "(in Python v3.10)") must be passed in that represents the image being uploaded. If this is done through a file then the file must be opened via `open('some_filename', 'rb')` and the [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object "(in Python v3.10)") is given through the use of `fp.read()`.

The only image formats supported for uploading is JPEG and PNG.

Changed in version 2.0: The edit is no longer in-place, instead the newly edited client user is returned...
sturdy tapir
#

It continued and didn't wait at all

#

I fixed it, forgot to remove the while loop

slate swan
#

how is stickybot so fast angery
server latency and library different don't account for how fast it is

signal canopy
#

is there a good way of creating a discord bot in python other than using discord.py

sturdy tapir
#
File  line 28, in on_ready
    await bounty_channel.send("***Resting for 5 seconds.***")
AttributeError: 'NoneType' object has no attribute 'send'
#

what's the problem?

coral geyser
#

Why do you have a send command in on_ready

sturdy tapir
coral geyser
#

if the bot crashes or goes offline

#

and it goes back online, it does the entire thing again

sturdy tapir
#

yeah that's ok

sick birch
#

Do you have any specific errors that I can help with?

signal canopy
sick birch
sturdy tapir
#
Traceback (most recent call last):
  File "C:\Users\IT Solutions\AppData\Roaming\Python\Python37\site-packages\discord\ext\tasks\__init__.py", line 101, in _loop
    await self.coro(*args, **kwargs)
  File "c:/Users/IT Solutions/Desktop/myprojects/bounty/bountybot.py", line 29, in on_ready
    await bounty_channel.send("***Resting for 5 seconds.***")
AttributeError: 'NoneType' object has no attribute 'send'

any known fix for this?

coral geyser
#
@client.command(aliases=["nickbot"])
@commands.has_permissions(manage_nicknames=True)
async def nicknamebot(ctx):
    await discord.ClientUser.edit(username=ctx.message)
    await ctx.reply("Changed username to " + ctx.message)
```It does nothing, it maybe loops on the first await but what did I index wrong?
sick birch
signal canopy
sick birch
#

Ah that's what you're looking for

signal canopy
#

yeah

#

that's the problem

sick birch
#

Well... I believe discord.js does let you read data from voice channels

#

The problem is it's not documented all that well even in the official API docs

signal canopy
sick birch
#

I'm not sure I understand

signal canopy
sick birch
#

@signal canopy if you're looking to recieve voice data, you're in a bit of a pickle

signal canopy
#

yeah i kinda noticed

sick birch
#

Even in discord's official documentation there's almost nothing about that

signal canopy
#

too bad

sturdy tapir
#
bounties = ["2887966607","700032621","1858461594"]
bounty_channel = client.get_channel(998183276084744232)
@tasks.loop(seconds=10.0)
async def on_ready():
    for bounty in bounties:
        req = requests.get(f"https://api.roblox.com//users/{bounty}").text
        list = json.loads(req)
        username = list["Username"]
        print(username)
        r = requests.get(f"https://api.roblox.com/users/{bounty}/onlinestatus/").text
        check = json.loads(r)
        status = check["LastLocation"]
        if status == "Playing":
            embed=discord.Embed(title="User Profile", url=f"https://roblox.com/users/{bounty}/profile", description=f"{username} is playing a game go check if it's da hood or not", color=0x7410b7)
            embed.set_author(name=f"{username}", url=f"https://www.roblox.com/headshot-thumbnail/image?userId={bounty}&width=60&height=60&format=png", icon_url=f"https://www.roblox.com/headshot-thumbnail/image?userId={bounty}&width=60&height=60&format=png")
            embed.set_thumbnail(url=f"https://www.roblox.com/headshot-thumbnail/image?userId={bounty}&width=60&height=60&format=png")
            await bounty_channel.send(embed=embed)
    await bounty_channel.send("***Resting for 5 seconds.***")
on_ready.start()

error :

fireisawfreind
FancySpirits
FDJDFHJIGJD
Unhandled exception in internal background task 'on_ready'.
Traceback (most recent call last):
  File "C:\Users\IT Solutions\AppData\Roaming\Python\Python37\site-packages\discord\ext\tasks\__init__.py", line 101, in _loop
    await self.coro(*args, **kwargs)
  File "c:/Users/IT Solutions/Desktop/myprojects/bounty/bountybot.py", line 29, in on_ready
    await bounty_channel.send("***Resting for 5 seconds.***")
AttributeError: 'NoneType' object has no attribute 'send'

Finishes all the tables and when it gets to the time were it sends to the "bounty_channel" it breaks

#

sorry for the flood.

signal canopy
#

thanks a lot

#

@sick birch

sturdy tapir
#

Anyone able to help?

sick birch
#

The first step is to set up a route handler that can get the code, which you'll exchange for the user's access token

sick birch
paper sluice
candid lodge
#

soooo ermmm

#

im new to coding

sick birch
#

Hard to tell without knowing what technologies you're using

#

I can't make it for you

#

I can tell you generally what to do, and help out with any specific errors you're having

candid lodge
#

and im gonna be learning python and i went to discord.py and it said to put this command: py -3 -m pip install -U discord.py to download the discord language and when i do it, it gives me all sort of errors what should i do

sick birch
#

That still doesn't really tell me anything. HTML, CSS, and JS files on their own are only good for static content, which is not good enough for making a log in with discord functionality

sturdy tapir
sick birch
candid lodge
sick birch
sick birch
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.

sturdy tapir
paper sluice
#

yes you can

sturdy tapir
#

thanks it works fine now

paper sluice
dense coral
#

I do not know what the problem is with my code

#

Error:

vale wing
unkempt canyonBOT
slate swan
#

or there are some dpy forks you can use.

#

seems like its already answered so nvm me

vale wing
slate swan
candid lodge
#

So i just started coding and it is giving me this error Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.

slate swan
candid lodge
#

thx

hardy yoke
candid lodge
hardy yoke
#

I mean it literally tells you lol

#

go into your windows settings > manage app execution aliases and disable the python shortcut

candid lodge
#

fixed it

coral geyser
#
# imports:
from math import perm
import random
import discord
from discord.ext import commands
from discord.utils import get

@client.command()
@commands.has_permissions(manage_messages=True)
async def mute(ctx, member: discord.Member):
    perms = discord.Permissions(permissions=65536) # permissions level for muted members
    if get(ctx.guild.roles, name="Muted | OhMan Bot"):
        print("Mute role exists")
    else:
        await ctx.guild.create_role(name="Muted | OhMan Bot", permissions=perms, colour=discord.Colour(0x0062ff))

    user = ctx.message.author
    role = get(user.server.roles, name="Muted | OhMan Bot")
    await member.add_roles(role)
```How would I assign a role to a user thats mentioned?
novel prairie
#

@bot.command()
async def test(ctx,*,text):
emojis = []
for s in text.lower:
if s.isdemical():
num2emo = {'0':'zero','1':'one','2':'two',
'3':'three','4':'four','5':'five',
'6':'six','7':'seven','8':'eight','9':'nine'}
emojis.append(f':{num2emo.get(s)}:')
elif s.isalpha():
emojis.append(f':regionalindicator{s}:')
else:
emojis.append(s)
await ctx.send(''.join(emojis))
i have this problem
i tried to recreate the emojify command and i get this message

File "main.py", line 190
elif s.isalpha():
^
SyntaxError: invalid syntax

dense coral
# novel prairie @bot.command() async def test(ctx,*,text): emojis = [] for s in text.low...

trying it:

@bot.command()
async def test(ctx,*,text):
    emojis = []
    for s in text.lower:
      if s.isdemical():
        num2emo = {'0':'zero','1':'one','2':'two',
                   '3':'three','4':'four','5':'five',
                   '6':'six','7':'seven','8':'eight','9':'nine'}
        emojis.append(f':{num2emo.get(s)}:')
      elif s.isalpha(): 
          emojis.append(f':regionalindicator{s}:')
      else:
          emojis.append(s)
      await ctx.send(''.join(emojis))```
There is a problem with the lines of code, I have fixed it.
dense coral
#

strftime, I have no idea why.

slate swan
coral geyser
#

I forgot that that exists. thanks

slate swan
#

Get discord.User avatar url ?

novel prairie
#

from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'builtin_function_or_method' object is not iterable

rapid falcon
#

hey

#

how to get a user mention in a specific channel?
for example when someone sends: "hello @rapid falcon"
i want the bot to get the mention @rapid falcon from the message

#

is there a way to do this? ping when replying

novel prairie
slate swan
#

with : ofcourse

#

im just telling to add a () after lower because its a callable

novel prairie
#

ok

#

thank you

dense coral
# novel prairie wait now it says this
@bot.command()
async def test(ctx,*,text):
    emojis = []
    for s in text.lower:
      if s.isdemical():
        num2emo = {'0':'zero','1':'one','2':'two',
                   '3':'three','4':'four','5':'five',
                   '6':'six','7':'seven','8':'eight','9':'nine'}
        emojis.append(f':{num2emo.get(s)}:')
      elif s.isalpha(): 
          emojis.append(f':regionalindicator{s}:')
      else:
          emojis.append(s)
    await ctx.send(''.join(emojis))```
Trying its working.
#

await ctx.send(''.join(emojis)) was in the wrong row.

slate swan
#

the lower is still wrong

#

!e print("AAAA".lower) # wrong
print("AAAA".lower()) # correct

unkempt canyonBOT
#

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

001 | <built-in method lower of str object at 0x7f73946ab2b0>
002 | aaaa
novel prairie
#

im new to coding sorry

dense coral
slate swan
#

indeed

novel prairie
#

it doesnt work

dense coral
novel prairie
#

from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'isdemical'

slate swan
#

its isnumeric

novel prairie
#

so i replace isdemical with isnumeric?

slate swan
#

yes

dense coral
slate swan
#

!e ```py
print("69".isdecimal())

slate swan
#

run python -V -V in your terminal

novel prairie
#

it didnt work

slate swan
slate swan
novel prairie
#

its working with numbers but i want to do this work with letters too

slate swan
#

You're missing the _

slate swan
#

Uhh okay so not bots related but discord, how do discord authenticates the users while they log in from typical login page? Like is it a type of grant from oauth just like for bots or they just give jwt tokens to user?

novel prairie
slate swan
#

The : is not correct

#

Look it by yourself...

#

x : -> x:

sick birch
#

\🇽

#

well that didn't work

#

:regional_indicator_x:

#

That's how it should be

novel prairie
#

emojis.append(f':regional_indicator_x :') i did this

slate swan
#

See the :

#

It's not right after the x

#

You have: x :
Needs: x:

novel prairie
#

oh ok leme try this again

slate swan
#

And you probably want to remove the x and put the actual letter instead

novel prairie
#

yea

slate swan
#

And I would check the length of the final message before sending, can easily get over the character limit

novel prairie
dense coral
# novel prairie

Everyone is confusing your mind, it's an easy thing and does not need everything they have written for you.

novel prairie
#

idk

#

can you sent me the code fixed cause its really confusing

dense coral
# novel prairie can you sent me the code fixed cause its really confusing
  emojis = []
  for s in text.lower():
    if s.isdecimal():
      num2emo = {"0": "zero", "1":"one", "2": "two", "3":"three", "4": "four", "5":"five", "6":"six", "7":"seven", "8":"eight", "9":"nine"}
      emojis.append(f":{num2emo.get(s)}:")
    elif s.isalpha():
      emojis.append(f":regional_indicator_{s}:")
    else:
      emojis.append(s)
  await ctx.send(' '.join(emojis))```
try
novel prairie
#

um ok

slate swan
#

Delete last 100 messages from a specific channel ?

#

emojis.append(f":{num2emo.get(s)}:") cross1

emojis.append(f":regional_indicator_{num2emo.get(s)}:")

slate swan
unkempt canyonBOT
#

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.

You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.

Changed in version 2.0: The `reason` keyword-only parameter was added.

Examples

Deleting bot’s messages...
slate swan
#

basically channel.purge() will do it for you

#

thanks

slate swan
#

nvm, youre correct

#

Is there a way to make voice channel private with command which channel has been created on another event?

   await voice.set_permissions(ctx.guild.default_role, view_channel=False, connect=False)
   if voice != None:``` `AttributeError: 'VoiceState' object has no attribute 'set_permissions'`
slate swan
#

also you should be checking if the voice is not None before changing perms

novel prairie
slate swan
#

would be a blessing if someone could help me

slate swan
novel prairie
#

same thing happens in the bot dank memer example: if you say pls emojify - it will sent -

dense coral
novel prairie
#

wdym

slate swan
#

can anyone make a bot that converts youtube to mp4s through discord 😭

novel prairie
slate swan
#

eh it's not that hard to download a youtube video

#

there are literally librairies for it

novel prairie
#

i know but its faster

slate swan
#

though might be against rule 5 as it's similar to music bots

#

not really

#

How to install discord.py from github using pip ?

#

behind the scenes, yes.

slate swan
#

i mean could you please help me? 😭

novel prairie
slate swan
#

Read the file, there is an example

#

you seem really good

slate swan
#

pip --- ?

#

Just look at it yourself?

slate swan
novel prairie
#

oh ok

slate swan
#

It's literally on the link

#

Take the 5 seconds to look at it yourself

#

You don't get everything given in life

slate swan
#

overwrite = ctx.channel.overwrites_for(member)

#

AttributeError: 'NoneType' object has no attribute 'id'

#

i dont understand why i get this error

slate swan
slate swan
#

they probably use some API or some kind of mapping which gets matching letters from other fonts

#

!e ```py
m = {
"a": "𝓪",
"b": "𝓫",
"c": "𝓬"
}
user_input = "bac"

do replacement stuff

hardy yoke
#

loop through the *, arg the user inputted

check the userinput against the dictionary

replace characters with the dict value

smoky sinew
#

stop using repl

#

easy fix

slate swan
#

could anyone help me make a youtube to discord mp4 converter command?

pliant gulch
#

Although, you would probably need to secure the index part more, incase of index error

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

Not exactly YTDL but the point applies

dusky pine
#

!src d

unkempt canyonBOT
#
Command: docs

Look up documentation for Python symbols.

Source Code
dusky pine
#

go look at it yourself 🙂

robust fulcrum
#

Hard to understand

#

I never did that insane code

dusky pine
#

seems like it does use an API

#

but can't find out which

robust fulcrum
dusky pine
#

yep they did web scraping

haughty nova
#

Hello, no errors but when I send the command !sregler the bot just removes the command but does not send anything

import discord
from discord.ext import commands
import asyncio
import random

TOKEN = "Token"

client = commands.Bot(command_prefix ="!")

@client.command()
@commands.has_role("regleraccess")
async def sregler(ctx,):
    await ctx.message.delete()
    embed = discord.Embed(title = "Gene's Regler", description = "Server Regler", color = 0x00FFFF)
    embed.add_field(name="§1 Man må ikke tigge om ting")
    embed.add_field(name="§2 Auto Clikker/Autosell er ikke tilladt")
    embed.add_field(name="§3 Racisme/nazisme tolerere vi ikke")
    embed.add_field(name="§4 Scamming er ikkee tilladt")
    embed.add_field(name="§5 Raiding er ikke tilladt")
    embed.add_field(name="§6 Reklame om andre servers er strengt forbudt")
    embed.add_field(name="§7 Max 2 account per ip")
    embed.add_field(name="§8 Alle former af hack er ikke tilladt")
    embed.add_field(name="§9 Kun Labymod, Lunar, Feather og badlion er tilladt")
    embed.add_field(name="§10 Staff ord er lov")
    embed.add_field(name="§11 Man må kun vinde 1 af baltop pladserne selvom man er i et team eller sig selv")
    embed.add_field(name="§12 Man må ikke booste andre udenfor sit team op på baltop")
    embed.add_field(name="§13 Støvsugning er ikke tilladt")
    embed.add_field(name="§14 Bots er ikke tilladt")
    embed.add_field(name="§15 Greif er ikke tilladt")
    embed.add_field(name="§16 Finder man en bug skal man oprette en ticket")
    embed.add_field(name="§17 Man må ikke sælge ting på serveren for emeralder")
    embed.add_field(name="§18 Brug dit sunde fornuft")
    embed.add_field(name="")
    embed.add_field(name="Vi skriver ud i #dev-log hvis det kommer nye regler")
    embed.add_field(name="")
    embed.add_field(name="© Superawesome")
    
client.run(TOKEN)```
sick birch
haughty nova
#

Sorry I don't understand what you mean with value

sick birch
#

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

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") for you.

Changed in version 2.0: `Embed.Empty` has been removed in favour of `None`.
haughty nova
sick birch
#

Inside the add_field

#

see the docs for more information

haughty nova
#

Okey thanks

cold tide
#
@commands.has_role("mod") 
async def addrole(ctx):
	 user = ctx.message.author 
	 role = discord.utils.get(user.server.roles, name="Test") 
	 await bot.add_roles(user, role)```
#

Anyone know the issue I cant use proper indentation due to my device.

drifting goblet
#

guy, i need your help. how 2 multiple file for discord bot

#

😭

worthy mortar
#

Your server needs 2 discord py bots?

drifting goblet
#

like all in 1

merry cliff
#

so is it 2 bots or 1 bot plsu an extension?

drifting goblet
#

i want to make music and moderator in 1 bot

#

sry iam newbie

dusky pine
#

Use cogs

drifting goblet
#

can i get that code

merry cliff
#

what ver of dpy are u using

drifting goblet
merry cliff
#

uh

#

thats that ur python version

drifting goblet
#

1.7.3

merry cliff
#

ok

#

make a new folder in the same directory called cogs

#

and put the extension into it

#

now in the main file, somewhere under your on_ready function, do bot.load_extension('cogs.filename without the .py at the end')

#

then in your cog file, setup a class: class className(commands.Cog):

#

then with each command instead of the @bot.commands decorator, use @commands.command

#

at the bottom of the file, do py def setup(bot): bot.add_cog(className(bot))

drifting goblet
merry cliff
#

no

drifting goblet
#

oh

sick birch
merry cliff
#

it can be anything, but usually something like commands

merry cliff
drifting goblet
#

ok

dusky pine
#

do it outside on_ready

#

like after you define your commands.Bot instance

merry cliff
#

yeah that works too

#

for example: ```py
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix ='>', help_command=None, case_insensitive=True, intents=intents)

load_dotenv()
TOKEN = os.getenv("UNSEEBOT_TOKEN")

bot.load_extension("cogs.meme")
bot.load_extension("cogs.tts")
bot.load_extension("cogs.tictactoe")

#

and in each command, there should be a self parameter before the ctx

drifting goblet
#

if i use client=command.Bot should i change it?

dusky pine
#

rename client to bot

merry cliff
#

yeah that is incorrect variable nameing but it won't break the bot

drifting goblet
merry cliff
#

no client to bot

#

not bot to client

drifting goblet
merry cliff
#

change the client to bot

#

but otherwisw keep it

#

!paste

#

here is an example of a cog

drifting goblet
#

tysm

trail cosmos
#

Hi I was wondering if anyone can help me. I am trying to make my discord bot send the contents of a .txt file. Can someone please help
this is for discord.py

shrewd apex
#

just send the file

#

!d discord.File

unkempt canyonBOT
#

class discord.File(fp, filename=None, *, spoiler=..., description=None)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.

Note

File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
rancid fiber
#

can someone help me to do a inventory bot? or tell me how i can do

kind trellis
#

How do I load all of my extensions at once in 2.0?

stiff fern
#

Anyone know how you send messages in threads w/ pycord

slate swan
#

that would be cool ig a method that takes a list of paths that are strings ofc, it would be kinda redundant but i can see the usage of it

kind trellis
slate swan
#

you cant load them all at once afaik, you would have a for loop which that isnt instant thats one after the other

slate swan
#

even disnake has it but I dont like disnake cause no

#

imagine still making bots🤨

#

totally not me

#

i moved on to networkingpithink

#

I moved on to overworking

#

anyways im going to read my course now bye

#

bye kid

#

dont call me a kid

#

if im a child i dont want to know what my grandma classifies as

#

tweenager

#

guess youre a child like mepithink

#

no im older

#

doesnt look like it🧍

#

ok.

#

!ot

unkempt canyonBOT
slate swan
stiff fern
#
class Main(commands.Bot):
    
    def __init__(self):
        super().__init__(
            command_prefix = ".",
            intents = discord.Intents.all(),
            application_id=996142024430452826) # Client ID

    async def on_ready(self):
        await bot.change_presence(activity=discord.Activity(
            type=discord.ActivityType.watching,
            name="the Nebula Network"))

        print(f'{self.user} has initialized.')


    async def setup_hook(self):

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

        # Guild ID
        await bot.tree.sync(guild=discord.Object(id=848367847670284298))

My extensions aren't loading anymore for some reason if anyone knows why

#

on_ready works tho

#

setup_hook doesnt even tho it worked before?

slate swan
#

what is even bot? its pretty messy code ngl

stiff fern
#

well I aint a professional so

#

idk what you mean what is bot

#

bot = Main()

#

i thought it was pretty clean 🥲

#

whats messy about it

slate swan
#

why would you call your subclass Main? and where is it defined in the class???

stiff fern
#

bc its the main file?

#

idk what would you call it

slate swan
#

Well your bots name?

stiff fern
#
import discord

from discord.ext import commands

class Main(commands.Bot):
    
    def __init__(self):
        super().__init__(
            command_prefix = ".",
            intents = discord.Intents.all(),
            application_id=996142024430452826) # Client ID

    async def on_ready(self):
        await bot.change_presence(activity=discord.Activity(
            type=discord.ActivityType.watching,
            name="the Nebula Network"))

        print(f'{self.user} has initialized.')


    async def setup_hook(self):

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

        # Guild ID
        await bot.tree.sync(guild=discord.Object(id=848367847670284298))


bot = Main()
#bot.run(os.environ["DISCORD_TOKEN"])

is how I have it setup

#

if that extra bit adds anything

slate swan
#

inside your class remove bot and pass self

stiff fern
#

you want me to remove commands.Bot?

slate swan
stiff fern
#

is it that complicated? 😭

slate swan
#

more like messy and unreadable

stiff fern
slate swan
#

yes

stiff fern
#

okay done

#

does that make it more readable 😂

#

or what else is wrong with it

slate swan
#

because bot is undefined in your class

stiff fern
#

oooh

slate swan
stiff fern
#

well I have a side question right

await bot.tree.sync(guild=discord.Object(id=848367847670284298))

What does getting this guild id actually do because I honestly am not sure and I don't know how you're suppose to do it where it sets the ID automatically so you dont have to manuallychange it for whatever server its in or if thats suppose to represent the main server or what

slate swan
#

probably to sync commands on one server idk check docs

#

¯\_(ツ)_/¯

stiff fern
#

Okay so I shouldnt need it basically

#

is what im checking

#

I would prefer things be universal

stiff fern
slate swan
#

checked docs and to sync slash commands globally you would use that methkd with no guild id

stiff fern
#

or do the setup hook

stiff fern
stiff fern
#
class Main(commands.Bot):
    
    def __init__(self):
        super().__init__(
            command_prefix = ".",
            intents = discord.Intents.all(),
            application_id=996142024430452826) # Client ID

    async def on_ready(self):
        await self.change_presence(activity=discord.Activity(
            type=discord.ActivityType.watching,
            name="the Nebula Network"))
        
        print(f'{self.user} has initialized.')


    async def setup_hook(self):

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


bot = Main()
bot.run(os.environ["DISCORD_TOKEN"])
#

It doesn't print

#

basically so nothing loads

slate swan
#

you need to sync your commands and print something when setup_hook gets triggered

stiff fern
#

How do you sync commands

slate swan
stiff fern
#

Ahh

#

Still doesnt work 😅

slate swan
#

did you checked if setup_hook gets fired?

stiff fern
#

it is not being fired and the have the sync cmd inside that hook

#

Because it has to be inside a async function

slate swan
#

well did you put a print statement after the function signature?

#

and youre running your bot right?

stiff fern
slate swan
stiff fern
stiff fern
slate swan
#

¯\_(ツ)_/¯

stiff fern
slate swan
#

you cant expect much

slate swan
#

he already did

slate swan
#

hm ic

stiff fern
#

The only thing that prints is has initialized and after

slate swan
#

maybe your cogs dirs are incorrect and errors arent being raised?

#

just dont make a bot at this point av_pepeExit

#

i see no issue tbhpithink

stiff fern
#

I have a on_command_error for each cog w/ raise error

#

and it doesn't give me any 🥲

#

actuallynvm I see what ur saying

#

but i wouldnt think so

#

but what do i know yk

slate swan
#

remove all your command errors

#

and just have one in your class you dont really need multiples btw

#

and what is self.tree?

#

shouldnt you define it? or something

stiff fern
#

well self is the bot isnt it?

#

the class

slate swan
#

i was asking about the attribute

#

what is this called agian 😭 0x0b8f867

stiff fern
#

oh theres a self.sync_commands method

slate swan
#

shouldnt you define it or something idk if it gets set idk havent worked with dpy2.0

#

how do i find it 😭

slate swan
#

like for the embed.

visual island
slate swan
#

YES

#

oh wait

#

why is the hexcode 9 chars🧍

visual island
slate swan
#

arent hexcodes 8 chars for colors?

visual island
#

uh yeah it should be 8 chars

slate swan
#

yeahpithink

#

no like 😭

visual island
#

use 0x as the prefix

slate swan
#

you need to add the 0x prefix

#

it converts it to a hexcode, but its actually a int type😳

#

different bases is the different between numbers and hexcodes right?

slate swan
#

add 0x to the start

#

0xF3A5F4 it should be

#

ohh

toxic fossil
#
def check(m: discord.Message):  
    return m.author.id == ctx.author.id and m.channel.id == ctx.channel.id

msg2 = await self.bot.wait_for('message', check=check, timeout = 60.0)

await ctx.send(msg2.content)```
I have this simple code and I was wondering how I could get a memberObject from a user that is mentioned inside of the message content, I remember there was some way but I cannot seem to find it on google or stack to help me
#

Ohhh its the msg2 var with a .mentions[] i'm slow asf

stiff fern
slate swan
#

hii can someone help me find where to put the embed color

heavy folio
#

you instantiated the embed correctly
check your indents

#

!indent

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

heavy folio
slate swan
last mica
stiff fern
slate swan
#

where do i put the embed thingi 😭

#

color embed

heavy folio
#

notice that embed = discord.Embed(... line's indentation did not match with the other lines

vocal snow
#

And you should change embed.color instead of creating a new Embed instance

slate swan
#

its already in the constructor?

slate swan
slate swan
slate swan
ivory owl
#

how do I load Jishaku with slashbot?

#

bot.load_extension('jishaku') is not working

#

and how do I mention aliases in @bot.hybrid_command(...,with_app_command=True)?
Because the function doesn't seem to take aliases as a parameter

ivory owl
#

bot.logout() is not working as well

slate swan
ivory owl
slate swan
#

!pip jishaku it's a library

unkempt canyonBOT
ivory owl
#

but how does that even work

slate swan
ivory owl
#

can I put it under setup_hook?

slate swan
#

Yeah sure

ivory owl
#

nice. that problem is now solved

ivory owl
slate swan
#

I think you can use the aliases kwarg in hybrid_commands decorator

#

!d discord.ext.commands.Bot.hybrid_command

unkempt canyonBOT
#

hybrid_command(name=..., with_app_command=True, *args, **kwargs)```
A shortcut decorator that invokes [`hybrid_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.hybrid_command "discord.ext.commands.hybrid_command") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.add_command "discord.ext.commands.Bot.add_command").
slate swan
#

Yeah it should work ( but only for prefix commands )

ivory owl
slate swan
#

slash commands don't have aliases so

ivory owl
#

did they change member.avatar_url to something else?

slate swan
#

member.avatar.url

ivory owl
#

bruh

slate swan
#

member.avatar returns a discord.Asset object which has a url property

ivory owl
#

oh

slate swan
#

AttributeError: module 'discord' has no attribute 'ui'

#

on_message function

async def on_message(self,message):
        view = discord.ui.View()
        style = discord.ButtonStyle.gray 
        item = discord.ui.Button(style=style, label="Atest",       url="https://docs.google.com/") 
        view.add_item(item=item)  

        ```
#

install 2.0 dpy

#

no

#

can you help @slate swan

#

RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
client.load_extension(extension)

#

and await can only work inside async functions

#
if __name__ == '__main__':
        for extension in coggs:
            client.load_extension(extension)
#

can someone help me out, i just switched to dpy 2.0

slate swan
#

can someone help me make a cmd that gives your members a role when ever they represent your server in their status

#
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'Cogs.mycogg' raised an error: TypeError: object NoneType can't be used in 'await' expression``` now it's throwing me this error without line number or anything
slate swan
#

🙂

slate swan
robust fulcrum
robust fulcrum
#

Hmm

#

I not know about that error

slate swan
slate swan
slate swan
slate swan
unkempt canyonBOT
#

property activity```
Returns the primary activity the user is currently doing. Could be `None` if no activity is being done.

Note

Due to a Discord API limitation, this may be `None` if the user is listening to a song on Spotify with a title longer than 128 characters. See [GH-1738](https://github.com/Rapptz/discord.py/issues/1738) for more information.

Note

A user may have multiple activities, these can be accessed under [`activities`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.activities "discord.Member.activities").
vocal snow
#

you need presence intents for this

robust fulcrum
slate swan
#

i guess discordpy 2.0 is not for me

vocal snow
placid skiff
#

Nope, status is online, offline and so goes on

vocal snow
placid skiff
#

activity are the background applications connected with discord

slate swan
#

hi

#

why he have staus "be right"

    activity = discord.Game(name="Bloons TD battles", type=3)
    await client.change_presence(status=discord.Status.idle, activity=activity)```
slate swan
#

please tag me if you find any fix

robust fulcrum
#

Means in your cog or main file

slate swan
slate swan
#

it will load without async def setup function in my cog?

#

rooPopcorn no

#

then?

proven ore
#
@company.sub_command(
        name="create",
        description="Create your company"
    )
    async def create(self, inter: disnake.ApplicationCommandInteraction):
        await inter.response.defer()
        company = db.Company(owner=inter.author)
        await company.exists()
        if company.exists:
            print("YES")
            await self.bot.send(inter, "Company already exists!", disnake.Color.red(), edit=True)
        else:
            print("NO")
            await self.bot.send(inter, "Company created! Manage your company using /company manage", edit=True)

command

    async def send(self, inter: disnake.ApplicationCommandInteraction, msg, clr=None, followup=False, edit=False):
        emb = disnake.Embed(description=msg, color = clr or self.color)
        if edit:
            return await inter.edit_original_message(embed=emb)
        elif followup:
            return await inter.followup(embed=emb)
        else:
            return await inter.send(embed=emb)

self.bot.send

the problem is, when i run the command
it shows "Bot is thinking..." for like 1 second
then interaction failed
but it does print "YES"
and it doesn't send anything
help?i tried removing defer() no change
i also tried removing edit=True

robust fulcrum
# slate swan then?
for cog in cogs:
        try:
            await bot.load_extension(cog)
            print(cog + " was loaded.")

Try this

slate swan
#
@client.event
async def on_ready():
    coggs = []

    for filename in os.listdir('./Cogs'):
        if filename.endswith('.py'):
            coggs.append("Cogs." + filename[:-3])
    for cog in coggs:
       await client.load_extension(cog)
``` main file

```py
async def setup(client):
    await client.add_cog(FivemStatus(client))``` cog
robust fulcrum
#

I really confused

slate swan
#

it loads all the cogs in the cogs folder

ivory owl
#

was there a change in bot.logout() in 2.0?

robust fulcrum
slate swan
slate swan
# robust fulcrum Can you show error again?

it was not showing any after making it async def but before it was

raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'Cogs.mycogg' raised an error: TypeError: object NoneType can't be used in 'await' expression```
#

now it's not showing any error

#

or working

slate swan
#

why he have staus "be right back"

    activity = discord.Game(name="Bloons TD battles", type=3)
    await client.change_presence(status=discord.Status.idle, activity=activity)```
#

what

#

there's no status

#

uhh

#

u see this moon i want green circle XD

#

moon....?

robust fulcrum
robust fulcrum
slate swan
# slate swan uhhh
activity = discord.Game(name="Bloons TD battles", type=3)
await client.change_presence(status=discord.Status.online, activity=activity)
shrewd apex
#

for a sec i read that as i want the moon green💀

robust fulcrum
#

😂

robust fulcrum
paper sluice
#

store the number the user types and see if its the same as the previous one, you will have to store it outside the scope of the function for it to work properly

#

do pfp = pfp.convert('RGB') before saving it

shrewd apex
#

thats one of the most dumb image manipulation in a command i have ever seen

#

best way would be to save as png

#

bro send the code as text

#

imagine two people using the command at the same time

#

pil is sync

#

and u are saving a file locally

#

then sending

paper sluice
#

first of all, have only one on_message event
then make my_variable a bot variable like bot.my_variable = 0 ( its not the best option )
then you check the message content and see if the message content is bot.my_variable + 1

shrewd apex
#
def process(data):
  wanted = Image.open("distract.PNG").convert('RGBA')
  pfp = Image.open(data).convert('RGBA').resize((300, 285), Image.LANCZOS)
  wanted.paste(pfp, (74, 190), pfp)
  buffer = BytesIO()
  wanted.save(buffer, "PNG", quality=95)
  buffer.seek(0)
  return buffer

@bot.slash_command(description="Wanted Image Manipulation")
async def distract(ctx, user: discord.Member = None):
    if not user:
        user = ctx.author
    data = BytesIO(await user.display_avatar.read())
    img = await bot.loop.run_in_executor(None, process, data)
    await ctx.respond(file=discord.File(img, "profile.png"))
paper sluice
#

message.channel.id == "997957555194171462" .id returns int so this condition will always be false

#

remove the "

#

in all of the ifs not just that condition

paper sluice
#

no? why would you do that?

slate swan
#

Hi im back from school 👋

shrewd apex
dusky pine
#

rip

unkempt canyonBOT
shrewd apex
#

where is ur umbrella?

paper sluice
#

also do message.content != bot.my_variable instead of ==

slate swan
paper sluice
#

and if you have this first

    if message.channel.id != 997957555194171462:
        return

you dont have to check the id in every if

slate swan
slate swan
#

👋

#

I'm not spamming

paper sluice
shrewd apex
#

yes sparky is helping to make this channel ot again

paper sluice
#

!ot

unkempt canyonBOT
shrewd apex
#

str == int is it possible?

slate swan
slate swan
shrewd apex
#

...

#

both of u either failed in english or in maths idk which

robust fulcrum
#

Is there any user mentioned event?

slate swan
#

!e

str = 1
int = 1 
print(str==int)
paper sluice
#

it will work, i just copied the old message 😅

unkempt canyonBOT
#

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

True
slate swan
#

See

shrewd apex
#

eh idk just check the docs

robust fulcrum
slate swan
#

¯\_(ツ)_/¯

shrewd apex
slate swan
#

Hehe jk

#

how to revert back to older version of dpy?

shrewd apex
#

👌

robust fulcrum
#

Is there any user mentioned event?

slate swan
shrewd apex
slate swan
slate swan
shrewd apex
#

or just pip install discord.py

#

since thats the last stable release

robust fulcrum
slate swan
#

thanks

shrewd apex
#

whats a trigger command?

slate swan
#

!d discord.Member.mentioned_in

unkempt canyonBOT
slate swan
#

Ye this

slate swan
shrewd apex
#

send ur code as text

slate swan
#

use cogs 😔

#

much better

shrewd apex
#

if message.content != bot.my_variable

#

message.content is str

slate swan
#

as you wish

robust fulcrum
shrewd apex
#

and bot var int it will never be equal

shrewd apex
#

capital letter at start of sentence

robust fulcrum
#

My keyboard did

slate swan
paper sluice
#

because you did message.content is a str not int

#

so comparison with int returns false

shrewd apex
#

wait a sec lemme rewrite it

robust fulcrum
slate swan
#

No

#

Like member.mentioned_in(message)

#
raise errors.ExtensionAlreadyLoaded(name)
discord.ext.commands.errors.ExtensionAlreadyLoaded: Extension 'Cogs.fivemstatus' is already loaded.``` but it's not loaded
robust fulcrum
shrewd apex
#

bot.my_variable = 275

@bot.event
async def on_message(message: discord.Message) -> None:
    if message.channel.id == 997957555194171462:
      if message.content != str(bot.my_variable+1):
          return await message.delete()
      else:
          bot.my_variable += 1
paper sluice
unkempt canyonBOT
#

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

001 | True
002 | True
shrewd apex
#

ok wonderful

#

u will go down in history with newton and einstein

#

store it somewhere

#

like a json or something

#

search google

#

┬─┬ ノ( ゜-゜ノ)

#

or just use a txt file

paper sluice
#

#bot-commands message

vocal snow
#

(╯°□°)╯︵ ┻━┻

paper sluice
#

stop before mods flip this channel :p

vocal snow
#

You want to send a custom emoji?

dusky pine
#

like that ^^

vocal snow
#

What's the purpose of that

shrewd apex
#

making gif with pil is a headache

#

it should be ez to make tho

#

all u need to do is change the image paste position

#

mm yeah

#

eh i can give u a rough idea how to

#

first u paste and make the triggered image

#

bro do one thing u see pil docs for image manipulation

#

its ez if u dont understand ask

#
with open("count.txt") as read_file:
    data = read_file.read()

bot.my_variable = int(data)

@bot.event
async def on_message(message: discord.Message) -> None:
    if message.channel.id == 997957555194171462:
      if message.content != str(bot.my_variable+1):
          return await message.delete()
      else:
          bot.my_variable += 1

@bot.command()
async def save_num(ctx):
    with open('count.txt', 'w') as f:
       f.write(bot.my_variable)
    await ctx.send("saved")
slate swan
#

ew

shrewd apex
#

its just one number

#

what else are u going to do

slate swan
#

might as well use a json file ASsip

shrewd apex
slate swan
#

why even use that, just write them manually on a paper

shrewd apex
#

exactly

#

why even write just memorize

#

its only one number

smoky marsh
#

Is it possible to add a docstring to a discord bot discord.py event?

#

Also, what's the difference between an event and a command

smoky marsh
slate swan
smoky marsh
#

Could you give me an example

shrewd apex
#

ashley explain in human language lmao

smoky marsh
#

Yes, human language

slate swan
#

whart

slate swan
stable leaf
#

how to get owner of a guild? ctx.guild.owner.mention doesn't work for me

shrewd apex
#
Declaring Docstrings: The docstrings are declared using ”’triple single quotes”’ or “””triple double quotes””” just below the class, method or function declaration. All functions should have a docstring.

Accessing Docstrings: The docstrings can be accessed using the __doc__ method of the object or using the help function.
stable leaf
#

oh

#

i think i have them tho

shrewd apex
#

enabled and in ur cods

#

code*

stable leaf
#
intents = discord.Intents.default()
bot = commands.Bot(command_prefix="-", intents=intents)
shrewd apex
#

u dont

stable leaf
#

and also in dev portal

shrewd apex
#

intents.member = True

stable leaf
#

ok

#

i'll try

#
Traceback (most recent call last):
  File "/Users/sgolis/PycharmProjects/Discord_Bot/main.py", line 12, in <module>
    intents.member = True
AttributeError: 'Intents' object has no attribute 'member'
#

error

shrewd apex
#

wait a sec lemme check the docs

#

its members

#

my bad

stable leaf
#

oh

shrewd apex
#

intents.members

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

bot = commands.Bot(command_prefix=prefix, intents=intents)
stable leaf
#

thx

#

it works now

smoky marsh
#
import discord
from discord.ext import commands

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

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

#Normal commands
@client.command()
async def f2c(ctx, fahrenheit:int):
    """This function converts Fahrenheit to Centigrade."""
    await ctx.reply(f"{fahrenheit} Degrees Fahrenheit is {(fahrenheit-32)*5/9} Degrees Centigrade", mention_author = True)

@client.command()
async def c2f(ctx, celsius:int):
    await ctx.reply(f"{celsius} Degrees Centigrade is {(celsius*5/9) + 32} Degrees Fahrenheit")

@client.command()
async def km2m(ctx, km:int):
    await ctx.reply(f"{km} Kilometers is {km*1000} meters")

@client.command()
async def m2km(ctx, m:int):
    await ctx.reply(f"{m} meters is {m/1000} kilometers")





#Docstring retrieval
@client.command()
async def help(ctx, input_doc):
    await ctx.reply(input_doc.__docstring__)
PS C:\Users\HP\Desktop\Discord Bots> & C:/Users/HP/AppData/Local/Programs/Python/Python310/python.exe "c:/Users/HP/Desktop/Discord Bots/discord_bot1.py"
Traceback (most recent call last):
  File "c:\Users\HP\Desktop\Discord Bots\discord_bot1.py", line 33, in <module>
    async def help(ctx, input_doc):
  File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 1485, in decorator
    self.add_command(result)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 228, in add_command
    super().add_command(command)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 1320, in add_command    raise CommandRegistrationError(command.name)
discord.ext.commands.errors.CommandRegistrationError: The command help is already an existing command or alias.```
smoky marsh
shrewd apex
#

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

smoky marsh
#

working, thanks, but what does it do, though? @shrewd apex

placid skiff
#

cLieNT = commands.Bot

smoky marsh
#
Traceback (most recent call last):
  File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 200, in wrapped     
    ret = await coro(*args, **kwargs)
  File "c:\Users\HP\Desktop\Discord Bots\discord_bot1.py", line 34, in help
    await ctx.reply(input_doc.__docstring__)
AttributeError: 'str' object has no attribute '__docstring__'

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

Traceback (most recent call last):
  File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1330, in invoke      
    await ctx.command.invoke(ctx)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 995, in invoke      
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 209, in wrapped     
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute '__docstring__'```
Uh oh
smoky marsh
placid skiff
#

nvm

smoky marsh
slate swan
#

!e

def uwu() -> None:
  ''' Blvck is uwu '''

print(uwu.__doc__)
unkempt canyonBOT
#

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

 Blvck is uwu 
shrewd apex
#
@client.command()
async def help(ctx, input_doc):
    await ctx.reply(input_doc.__docstring__)
#

💀

shrewd apex
#

my eyes

smoky marsh
shrewd apex
#

thats not how u make a help command...

smoky marsh
#
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.str() (if defined)
or repr(object).
encoding defaults to sys.getdefaultencoding().
errors defaults to 'strict'.```
smoky marsh
slate swan
smoky marsh
#

I wanted to make a docstring retrieval

#

Because yes help

slate swan
#

do you know what a docstring is

placid skiff
#

commands have a description parameter D_D

smoky marsh
smoky marsh
#

You see I'm very inexperienced

placid skiff
#

in the command decorator
@bot.command(name="uwu", description="this command does uwu thing")

slate swan
#

'cause yes

smoky marsh
placid skiff
#

duh no, you need the command object

#

!d discord.ext.commands.Command

unkempt canyonBOT
#

class discord.ext.commands.Command(*args, **kwargs)```
A class that implements the protocol for a bot text command.

These are not created manually, instead they are created via the decorator or functional interface.
slate swan
smoky marsh
slate swan
smoky marsh
faint sapphire
#

is it possible for a bot to get the id of a server if its given an invite link?

smoky marsh
#

@slate swan

slate swan
#

what

smoky marsh
alpine pewter
#

I had a quick question if anyone can help.
If I have two @tasks.loops and wanted one to run after the first one is complete, how would I do that? I've tried a few methods, can't seem to get it right. Figured to ask before looking again 😄

Here are their names --

    online_players.start()
    status.start()
slate swan
smoky marsh
smoky marsh
#

I couldn't understand anything 😄

slate swan
slate swan
#

f

alpine pewter
#

I tried with the if not status.is_running() and couldn't get it to work. Would there be a better way?

slate swan
#

why do people always have an issue with is_running not working 😔 and no

alpine pewter
#

I might've just messed it up tbh 😄

#

Here's my starting code, one moment

faint sapphire
#

is it possible to make a bot read whats in an embed message

i want a bot to read the number of members in the embed of an invite

shrewd apex
#

message.embeds[0].to_dict()

alpine pewter
slate swan
#

it wont be accessible if it was embedded automatically from a link

alpine pewter
#

I tried without ;-;

#

I think, probably not

#

Okay, gonna let it run the (hopefully) proper way and I'll let you know if I still struggle kek

#

Yeah, I'm pretty sure I'm just not doing it right.
I put it at the end of my code. The status starts fine but the online_players doesn't seem to start. So, I'm assuming I'm just doing it wrong? @slate swan

status.start()
if not status.is_running():
    online_players.start()
slate swan
#

might as well put the conditional inside another task

#

and start that task

#

@tasks.loop(seconds=5)
async def status_check() -> None:
  await bot.wait_until_ready()
  if not status.is_running():
    online_players.start()

status.start()
status_check.start()
alpine pewter
slate swan
#

Nor did I ASsip welcome

cold sonnet
#

and why do y'all put if not

slate swan
cold sonnet
#

what

cold sonnet
#

maybe I joined too late, I don't see where bro stops the task

#

little did I know the case is solved already

alpine pewter
# slate swan Nor did I <:ASsip:661284386439954433> welcome

So, I tested it some more a few ways. The code works but it doesn't register the status as being done. Here's the code I was tweaking to see if it would log something --

@tasks.loop(seconds=5)
async def status_check() -> None:
    await bot.wait_until_ready()
    print("Test")
    if not status.is_running():
        online_players.start()
        print("online_players.start()")
cold sonnet
#

how do you stop status

slate swan
#

^

alpine pewter
#

... You have to stop it? 💀

slate swan
#

yes...?

alpine pewter
#

I thought it did automatically after the loops

#

I feel so stupid

cold sonnet
#

what loops

vocal snow
#

I see Ashley is confusing everyone as usual

cold sonnet
#

if you didn't specify the amount it's infinite

alpine pewter
#

Idk, I guess my mindset was (even tho it was wrong)
The @tasks.loop(seconds=300) would stop it after the code finishes, then start it after 300s.

#

I shall fix, ty

cold sonnet
#

yeah...

#

it counts as running

rapid falcon
#

how to get a user mention in a specific channel?
for example when someone sends: "hello @rapid falcon"
i want the bot to get the mention @rapid falcon from the message

cold sonnet
#

!d discord.Message.mentions

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.

cold sonnet
#

if you use message.mentions, you get a list of members

rapid falcon
#

Latest mentions, right?

cold sonnet
#

?

rapid falcon
#

I get a list with the latest mentions, right??

vocal snow
#

What are the latest mentions

cold sonnet
#

a list of the members who were mentioned in THAT message

rapid falcon
#

Ohhh

cold sonnet
#

say you have an on_message event

#

the on_message takes in the message someone sent

#

you can check the mentions of that registered message

#

I'm not sure what happens if someone's pinged multiple times

#

if there are no mentions I assume it's just an empty list

rapid falcon
#

How to mention the user back?

cold sonnet
#

or if it's a response

cold sonnet
rapid falcon
#

Pinged one

novel prairie
#

@bot.command()
async def avatar(ctx, *, avamember : discord.Member=None):
userAvatarUrl = avamember.avatar_url
await ctx.send(userAvatarUrl)

cold sonnet
#

you get that person in the list, so you can get that Member object which has the mention property:

members = message.mentions
member = members[0]
await message.channel.send(member.mention)
#

assuming this is an on_message

novel prairie
#

the command avatar works for me but i want to make the command say something like this when the user doesnt tag someone !avatar and the bot says you have to mention someone for this command to work

rapid falcon
#

Oh

novel prairie
#

how can i do this?

rapid falcon
#

I didnt know about user.mention

#

Thanks @cold sonnet
You should definitely become a helper

cold sonnet
cold sonnet
#

check if it's None

#

you have already set it oh

novel prairie
#

sorry idk how to do this im new to developing

novel prairie
cold sonnet
#
@bot.command()
async def avatar(ctx, *,  avamember : discord.Member=None):
    userAvatarUrl = avamember.avatar_url
    await ctx.send(userAvatarUrl)
```this is your code, if someone doesn't ping anything, avamember is None
#

do you know how to check if something is None?

novel prairie
#

um no

#

lol

cold sonnet
#

well that's not good but lol

#

if avamember is None:

#

in this case, you'd want to send a message

#
@bot.command()
async def avatar(ctx, *,  avamember : discord.Member=None):
    if avamember is None:
        return await ctx.send("You have to mention a user to do this! ")
    userAvatarUrl = avamember.avatar_url
    await ctx.send(userAvatarUrl) 
#

ok I was not sure how to not spoonfeed

rapid falcon
cold sonnet
#

I recommend learning the basics of python before going into discord bots though

slate swan
#

but why

novel prairie
#

can i make this same the same but when i mention a role?

cold sonnet
slate swan
cold sonnet
#

error handling is harder

slate swan
#

ew

cold sonnet
#

especially when checking if something's None needs assistance

#

no offence

novel prairie
#

ok

slate swan
#

upto your own convenience anyways

cold sonnet
#

but what if you want a different message for every command

slate swan
#

why would you need that + easily configurable using a dict

cold sonnet
#

I mean, you can check for the annotation of the MissingRequiredArgument to send the message you want

#

!d discord.ext.commands.MissingRequiredArgument

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/latest/ext/commands/api.html#discord.ext.commands.UserInputError "discord.ext.commands.UserInputError")
cold sonnet
#

param property on this

#

!d discord.ext.commands.Parameter.annotation

unkempt canyonBOT
slate swan
#

ofcourse you can do this

cold sonnet
#

you cannot expect this from a beginner

slate swan
#

cuz MissingRequiredArgument.param returns an inspect.Parameter

cold sonnet
#

idk I was quite surprised they made it easier

cold sonnet
cold sonnet
#

!d discord.ext.commands.Parameter

unkempt canyonBOT
#

class discord.ext.commands.Parameter```
A class that stores information on a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")'s parameter.

This is a subclass of [`inspect.Parameter`](https://docs.python.org/3/library/inspect.html#inspect.Parameter "(in Python v3.10)").

New in version 2.0.
slate swan
#

ic

cold sonnet
#

yes

#

class discord.ext.commands.Parameter

A class that stores information on a Command's parameter.

This is a subclass of inspect.Parameter.

New in version 2.0.

slate swan
#

nvm, wrong emoji

cold sonnet
#

it was definitely a typo

slate swan
#

prefix commands parsing sucks

cold sonnet
slate swan
cold sonnet
#

oh

slate swan
#

it used to be inspect.Parameter

slate swan
slate swan
cold sonnet
slate swan
slate swan
#

tbh i like inspect.Parameter more, useless subclassing

cold sonnet
#

technically discord is a module as well

slate swan
#

but not maintained

cold sonnet
#

can't you install it in 2.0?

slate swan
#

no

slate swan
#

!pip discord

unkempt canyonBOT
slate swan
#

nice summary

#

!pip discord2 noone feats this

unkempt canyonBOT
cold sonnet
#

what is this

slate swan
#

discord 2

cold sonnet
#

no shit

slate swan
#

!pip discord.js yes.

unkempt canyonBOT
slate swan
#

djs pepeShy

cold sonnet
#

it's actually pycord

#

ew

slate swan
paper sluice
slate swan
#

!pypi ACord

unkempt canyonBOT
slate swan
#

better

#

ik that guy lmao

vocal snow
#

ik that guy too

slate swan
#

weirdos

vocal snow
#

hes in my friends list i think

novel prairie
#

@bot.command()
async def join(self, ctx):
if ctx.author.voice is None:
return await ctx.send("You are not connected to a voice channel")
else:
channel = ctx.author.voice.channel
await channel.connect()
await ctx.send(f"Connected to voice channel: '{channel}'")

#

i wanted to make a join vc command

cold sonnet
#

this is becoming a music bot

novel prairie
#

and it says that im missing something

slate swan
#

I mean it could be

novel prairie
#

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

cold sonnet
vocal snow
#

why else would it join a voice channel

cold sonnet
#

remove self, you use that in classes

slate swan
cold sonnet
novel prairie
slate swan
#

or soundboards

vocal snow
#

there's /tts

slate swan
#

cz why not

cold sonnet
vocal snow
paper sluice
novel prairie
slate swan
vocal snow
slate swan
#

nice idea

#

I still dont get the idea why people make music bots

novel prairie
vocal snow
cold sonnet
#

just remove self @novel prairie

slate swan
novel prairie
#

ok

slate swan
#

instead just gift spotify premium to the users and tell them to start a group session

#

ash will gift free premium plans to all of us

#

I dont even buy one for myself, am poor

vocal snow
#

we should get the family plan

novel prairie
#

its not working

#

@bot.command()
async def join(ctx):
if ctx.author.voice is None:
return await ctx.send("You are not connected to a voice channel")

slate swan
#

maybe ur bot is lazy

slate swan
novel prairie
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: RuntimeError: PyNaCl library needed in order to use voice

slate swan
#

!pip pynacl install this

unkempt canyonBOT
#

Python binding to the Networking and Cryptography (NaCl) library

slate swan
#
pip install discord.py[voice]
cold sonnet
#

2.0?????????

vocal snow
#

what

novel prairie
cold sonnet
#

shouldn't you install it with 2.0

vocal snow
#

oh god

slate swan
#

I'm out

slate swan
# cold sonnet 2.0?????????
$ git clone https://github.com/Rapptz/discord.py
$ cd discord.py
$ python3 -m pip install -U .[voice]
``` you can do this in that case
cold sonnet
#

in the terminal

novel prairie
#

bruh idk what terminal is

slate swan
#

.......

#

shell/console/cmd.exe

novel prairie
#

like i said im new to dev