#discord-bots

1 messages Β· Page 793 of 1

slate swan
#

did you save and rerun the code>

rare saddle
slate swan
#

show current code

rare saddle
slate swan
#

and the error that it prints?

rare saddle
slate swan
#
bot = commands.Bot(stuff_you_have_already , sync_permissions=True)
slate swan
#

thats your issue now, old error has been fixed

#

no wait

slate swan
novel bolt
#

hey , if i use prefix and then type some words separated with space, on using on_command_error i was only able to get the first arg , So
if i use > hi hello ,so it possible to get the whole thing , hi hello

rare saddle
slate swan
#

pip install -U disnake

slate swan
rare saddle
slate swan
#

now rerun it

rare saddle
slate swan
#

yep

novel bolt
rare saddle
slate swan
#

since it comes from library internals

novel bolt
#

should i sent?

slate swan
novel bolt
#

using commands.command

slate swan
#

great. show the current code

novel bolt
#

ok

slate swan
#

cool

novel bolt
#
    @commands.command('tts')
    async def tts(self,ctx,*,message):      

        is_added= check_guild(ctx)
        
        if not is_added:
            value = {f"{ctx.guild.id}": "en"}
            with open("langs.json", "r+") as file:
                data = json.load(file)
                data.update(value)
                file.seek(0)
                json.dump(data, file)            

        try:
            language = json_lang(ctx)
            myobj = gTTS(text=message, lang=language,tld='com.au', slow=False)
            myobj.save(r"moosik/message.mp3")

            try:
                await ctx.author.voice.channel.connect()
            except:
                pass        

            if ctx.author.voice is None:
                return await ctx.send('Pls join a voice channel')           

            guild = ctx.guild
            voice_client: discord.VoiceClient = discord.utils.get(self.bot.voice_clients, guild=guild)
            audio_source = discord.FFmpegPCMAudio(r'moosik/message.mp3')
            if not voice_client.is_playing():
                voice_client.play(audio_source, after=None)
            else:
                await ctx.reply('Command not done')
                        
        except Exception as e:
            await ctx.send(e) 
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

novel bolt
slate swan
#

since you already use try/except there

novel bolt
#

i was only ablt to get hi out of it , so

boreal ravine
#

use * before the parameter to pass every argument after that into one parameter

slate swan
#

thats weird since you already have * before message kwarg

novel bolt
#

like this?

slate swan
#

yea

novel bolt
#

but it gave an error b4, lemme try again

slate swan
#

oh i get it, shouldnt you use >tts hi how r you?

#

if you want it to work as > hi how r you , you'll need to go for on_message listener

novel bolt
#

means?

novel bolt
novel bolt
#

i completely forgot abt it

#

then i will use tat method

novel bolt
slate swan
#

remove that *

novel bolt
#

btw thanks , i will do with on_message

steady ember
#
webhook = await ctx.channel.create_webhook(name="ubBot",avatar="https://images.unsplash.com/photo-1494253109108-2e30c049369b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8cmFuZG9tJTIwZm9vZCUyMHN0b3JlfGVufDB8fDB8fA%3D%3D&w=1000&q=80")```
#

is it correct way to use?

cobalt jacinth
#

how can i not let the user use the command twice in a row till current is timeout or completed

mystic carbon
#

Can you help?discord.ext.commands.errors.ExtensionNotFound: Extension 'Cogs.Code' could not be loaded.

#

There is a bot that is salvaged and they shared the code to the public and I want to start it myself and I got the zip file

#

And it gives this error

steel kindle
#

bot

plush crypt
steel kindle
#

does pycord or nextcord work

cobalt jacinth
#

help me pls

cobalt jacinth
slate swan
#

why dont you just use a cooldown?

twilit ocean
#

not for the command user

slate swan
#

no?

#

cooldowns provide buckets

cobalt jacinth
#

this worked

slate swan
#

Bad indents though

split minnow
#
async def on_reaction_add(message,user):
  await message.delete()```

Hey, I want that my bot deletes messages when there is a reaction on it. It doesnt work with my code. I know this is very basic but I'm new and i couldn't find a answer on stckoverflow or on reddit. So thank you
slate swan
#

you can do reaction.message.delete()

#

!d discord.Reaction.message

unkempt canyonBOT
split minnow
#

if I use reaction and user as parameters, the message. is underlined and i can't run the code either

#

it works thanks to you both

exotic patrol
#

I believe there are error handlers about it, UserMissingPermissions something...

#

let me search it on my bot

#

so wait, you want to check whether the bot has permissions or the user using that commend have permissions?

#

so it was BotMissingPermissions, but it didn't worked for me when I used it

flint steeple
#

Which one should I use nextcord or disnake to easily add new features to my bot ?

slate swan
outer flint
#
import disnake
from disnake.ext import commands
from disnake import Embed
import json


class ASE(commands.Cog):
    """Ages and Splendor Expanded"""
    def __init__(self, bot):
        self.bot = bot

    @commands.group(case_insensitive=True)
    async def ase(self, ctx):
        """Returns the ASE steam page"""
        if ctx.invoked_subcommand is None:
            ase_embed = Embed(title='Ages and Splendor Expanded',
                                url='https://steamcommunity.com/sharedfiles/filedetails/?id=2172666098',
                                description='I Has Ages!',
                                colour=0xd5000,
                                author='Made by Melvasul',
                                image='https://steamuserimages-a.akamaihd.net/ugc/1455177151331418092/0F4DB958BCA9F63CBC5B03EFCFCDBBE88093CEF5/?imw=268&imh=268&ima=fit&impolicy=Letterbox&imcolor=%23000000&letterbox=true')
            await ctx.send(embeds=ase_embed)

is there anything wrong here?

slate swan
rancid stump
#

Hy guys how i can means my personal account can join a discord server using python??

#

Where should i look to solve this problem

slate swan
#

!rule 5 , automating user account violates tos

unkempt canyonBOT
#

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

red sundial
rancid stump
#

I didn't know that

#

Means that something is not possible with discord ??? Api??

fervent shard
#
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: type object 'Colour' has no attribute 'pink'```
?????
final iron
#

Leave

rancid stump
fervent shard
# final iron Send the code
@bot.command()
async def cba (ctx):
  embed=discord.Embed(title="2. trolling, baiting & harassment", description="behaviors to intentionally start conflict or elicit negative reactions is considered trolling. \nthis includes but is not limited to sending abusive direct messages (DMs) to other users or players, purposely trying to bait a user into an argument, name calling, and actively trying to upset or cause arguments.", colour= discord.Colour.pink())
  await ctx.send(embed=embed)```
pastel lake
#

lmao cba

fervent shard
pastel lake
#

oh, you did, cba is cant be arsed, uk slang xD
yk how you come accross some repos and thier commit messages are like "fuck this im done" or "test" or just "asf"

#

i thought thats what you did xD

pastel lake
#

lmao

final iron
#

Fuck

pastel lake
#

L

#

just google fam

final iron
#

!d discord.Colour

unkempt canyonBOT
#

class discord.Colour(value)```
Represents a Discord role colour. This class is similar to a (red, green, blue) [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)").

There is an alias for this called Color...
final iron
#

Just enter in the hex

#

Or

#

Use another color

honest vessel
#

u can use any hex color

trim moss
honest vessel
#

this is how i do

final iron
#

I would recommend disnake

honest vessel
#

afile.py

colors = {"blurple" : 0x7289DA, "green" : 0x33ff57, "yellow" : 0xFFD300, "red" : 0xB22222}

acog.py

from cogs import afile
...
em = discord.Embed(title="", description="", colour=afile.colors["blurple"])
#

could prob place em in a better folder ducky_angel

boreal ravine
slim ibex
#

interesting

modern fiber
#

It pings role like this... how do I fix it?

#

await message.channel.send(f"Hey @half iron! Make sure to check this server out!")

#

Help?

boreal ravine
#

role or member

modern fiber
#

role

honest vessel
#

"The best API wrapper for discord you will ever need." kek right

#

@modern fiberformat is wrong, <@&id_of_role_here>

#

@cedar smeltcan u show ur parameters?

#

try msg = await ctx.response.send_message()

#

oh wait u using disnake or?

#

cause that is disnake i gave ^^

maiden fable
#

πŸ‘€

honest vessel
#

well it dosnt have that attributes

maiden fable
#

Show yr code

#

Seems like msg.author is None

#

await ctx.response.send_message wil return None

#

!d disnake.Interaction.original_message

unkempt canyonBOT
#

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

Fetches the original interaction response message associated with the interaction.

Here is a table with response types and their associated original message...
honest vessel
#

slashcommands uses interaction not ctx like normal messages

#

"This function is a coroutine."

final iron
#

When I get home from school I think I'm going to work on creating a welcome card feature

honest vessel
#

@cedar smelthere,

#

so instead of response.send_message() use the followup.send caue it returns a msg object

maiden fable
#

Sure

honest vessel
#

or that, both will get u a messageobject

#

that will use a webhook (for ur info)

#

just fetch it like u had

#

np

#

@cedar smeltbut u also have this what i see

#

aka ctx.message

#

so seems like no need of fetching orginal message

slate swan
#

what is .flatten() in this line: ** await ctx.channel.history(limit=num).flatten()**

glacial zealot
#

!d discord.AsyncIterator.flatten

unkempt canyonBOT
#

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

Flattens the async iterator into a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") with all the elements.
glacial zealot
#

Basically, it will fetch all of the messages up to that limit and put it in a list

slate swan
#

join my server😜

tidal hawk
#

Can somebody recommend database for storing XP (gaining xp by chatting)
is just using JSON okay?

honest vessel
#

aiosqlite

daring olive
#

!warn 933338635720351814 don't advertise or self-promote on our server as per our #rules

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied warning to @slate swan.

slate swan
#

or if you want to keep it like json, use mongodb

#

!pip motor

unkempt canyonBOT
slate swan
#

!pip aiosqlite

unkempt canyonBOT
tidal hawk
#

Thanks! Just asking, what are the downsides of using JSON as a database?

slate swan
maiden fable
#
  1. Used by Hunter
slate swan
#
  1. He caches stuff too
crystal comet
#

Nice

fresh iron
#

RuntimeWarning: coroutine 'ClientSession.close' was never awaited

#

whats this

fresh iron
#

classified

maiden fable
final iron
#

Are you seriously paranoid someone is going to steal it?

#

Or is it something to breaks tos?

#

I'm leaning towards the latter

honest vessel
#

that error is self explained

#

no need for code but intressting he scared of showing it, but answer is ||was never awaited||

fresh iron
final iron
#

Nobody is going to steal your code

fresh iron
#

i know i already solved it

honest vessel
#

am not sure - but why not use specific errorhandlers for specific commands?

#
    @commands.command(aliases=["b"])
    @commands.has_permissions(ban_members=True)
    async def ban(self, ctx, user:discord.User):
        ...
        await ctx.guild.ban(user, reason=reason)

    @ban.error
    async def ban_error(self, ctx, error):
        if isinstance(error, commands.MissingPermissions):
            await ctx.send(f"{ctx.author.mention} *You Missing Permissions.*")
        elif isinstance(error, commands.MissingRequiredArgument):
            await ctx.send(f"{ctx.author.mention} *You didnt mention {error.param}*")
``` kinda like this
#

@cedar smelti just know error.param dont know how to grab what command it was but that is an example of a command specific error

cold sonnet
#

okay the missing permissions one why

honest vessel
#

@cold sonnetjust example

cold sonnet
#

just do it in a global one

#

can you check for the typehint of a param?

honest vessel
#

ah then u better use global πŸ˜„ (thanks for letting us know when u find the answers of ur own questions)

#

damn 100 slashcommands....

#

is that max allowed or ?

pallid mango
#
@commands.command('role')
  @commands.has_permissions(kick_members=True) #permissions
  async def role(ctx, user : discord.Member, *, role : discord.Role):
    if role.position > ctx.author.top_role.position: #if the role is above users top role it sends error
      return await ctx.send('**:x: | That role is above your top role!**') 
    if role in user.roles:
        await user.remove_roles(role) #removes the role if user already has
        await ctx.send(f"Removed {role} from {user.mention}")
    else:
        await user.add_roles(role) #adds role if not already has it
        await ctx.send(f"Added {role} to {user.mention}")

  @commands.command('role')
  @commands.has_permissions(kick_members=True) #permissions
  async def role(ctx, user : discord.Member, *, role : discord.Role):
    if role.position > ctx.author.top_role.position: #if the role is above users top role it sends error
      return await ctx.send('**:x: | That role is above your top role!**') 
    if role in user.roles:
        await user.remove_roles(role) #removes the role if user already has
        await ctx.send(f"Removed {role} from {user.mention}")
    else:
        await user.add_roles(role) #adds role if not already has it
        await ctx.send(f"Added {role} to {user.mention}")```
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: role_error() takes 2 positional arguments but 3 were given and im getting this error, its in a cog and everything else in the cog works

#

oops i sent the code wrong

honest vessel
#

u forgot self

pallid mango
#
@role.error
  async def role_error(ctx, error):
    if isinstance(error, MissingPermissions):
      await ctx.send('**:x: | You do not have permission to use this command!**')```
pallid mango
honest vessel
#

if cog == class, u need self

#

as first parameter

#

def test(self, "just a string"):

pallid mango
#

where would i put that

honest vessel
#

async def role_error(self, ctx, error):

#

like that on all ur functions

oblique adder
#

What could be disadvantages of using rasp pi rahter than a vps to host a discord bot (8gb to be exact)

pallid mango
#

oooh

#

let me try that

split minnow
#

idk what I should do, my bot isnt working anymore

oblique adder
oblique adder
split minnow
honest vessel
#

uptime or memory, but your with 8GB is fine

oblique adder
split minnow
#

ok thanks

oblique adder
honest vessel
#

i use 512MB ram for my bots

#

its enough for me

pallid mango
#

and its not giving an error

honest vessel
#

@pallid mangodid u put self on the command too

oblique adder
pallid mango
#

no it works now

#

thank you

honest vessel
#

πŸ˜›

pallid mango
#
  @commands.command(pass_context=True, help = 'Delete messages!')
  @commands.has_permissions(kick_members=True)
  async def purge(ctx, limit: int):
          await ctx.channel.purge(limit=limit)
          await ctx.send(f"{ctx.author.mention} has cleared `{limit}` messages!", delete_after=5)
  @purge.error
  async def clear_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
      await ctx.send('**:x: | You do not have permission to use this command!**')
#

and now im getting the same error

honest vessel
#

self...

pallid mango
#

but do i put self here too

honest vessel
#

i told u to put self on all ur commands if they are in a cog

pallid mango
#

oh, i didnt know because it was a purge command

honest vessel
#

it dosnt matter what function it is

#

@pallid mangoif u learned how to make a basic class in python you would know this πŸ™‚

pallid mango
#

i just watched randoms on youtube

honest vessel
#

self, is instance of a class so u can reach methods n attributes in a class

cold sonnet
#

WeirdDoggo this me when youtube

pallid mango
#

i learn best by fixing mistakes and customizing commands

honest vessel
#

well u learn best with knowing basic python πŸ˜›

timid wagon
#

Knowing how subclassing works will help you learn better then

honest vessel
#

and then start do little more advanced python

#

Its not even that much of reading to learn the basics of python

#

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

honest vessel
pallid mango
#

okay

#

thank you

honest vessel
#

but if u still like watching youtube, theres plenty of PYTHON learning videos - not just some guy with outdated discord.py showing little codes without explaining much

#

that will just make u copy pasta n dont know much

unkempt canyonBOT
#

Hey @earnest ingot!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

earnest ingot
#

Who can help me with this code? Somehow it gets error, but everything is fine

honest vessel
#

show error

#

and also why this imports

earnest ingot
#

Wait

honest vessel
#

import random

from random import choice

#

use either one of em πŸ˜›

earnest ingot
honest vessel
#

you can remove import random

#

and keep the other but then u have to change one part

#

{random.choice(responses)} to choice(responses)

#

choice(status)

#

you using both, probally copy pasta n no clue πŸ™‚

#
import random
random.choice()

# OR
from random import choice
choice()
#

i would recommend use last cause that saves u from import unneccesary functions you dont need from random lib

earnest ingot
#

Ok, I'll try

honest vessel
#

@earnest ingotbut wat was yor error?

earnest ingot
#

RuntimeError: Event loop is closed

earnest ingot
slate swan
#

what things i should master in discord py to build discord bots

velvet tinsel
slate swan
#

no i mean things to build discord bots

#

@velvet tinsel

velvet tinsel
#

uhh…

#

they are?

earnest ingot
#

discord

#

random

velvet tinsel
#

you need to know some stuff about these to build a discord bot

velvet tinsel
earnest ingot
#

Try "pip install discord"

velvet tinsel
velvet tinsel
velvet tinsel
#

Idk actually, maybe the above comment?

earnest ingot
#

Okay, asyncio may be

#

But because of one error I'm in JavaScript, so that's why I am on this server

slate swan
#

no what discord py library components

honest vessel
#

@earnest ingotwell i tried help u with the most fundamental import of python modules, but that was too hard πŸ™‚

earnest ingot
#

I kno

#

Maybe try become helper or failed?

honest vessel
#

yeah its my fault, not yours.

earnest ingot
#

?

#

Why

honest vessel
earnest ingot
#

Wdym

honest vessel
#
import random
random.choice()

# OR
from random import choice
choice()

you use both of those instead of 1.

import random
from random import choice
await ctx.send(f'Question: {question}\nAnswer: {random.choice(responses)}')

    await client.change_presence(activity=discord.Game(choice(status)))
earnest ingot
#

Wrong code I sent to you, but now worked

honest vessel
#

well do u understand what i even mean?

earnest ingot
#

Ye, that when I type one addon twice, Python says: "Get the f||or||k out"

honest vessel
#

ok, good luck with your coding πŸ™‚

rustic onyx
#

I wanna code a welcome cog that sends something like this when someone joins the server, any idea on how can I code it? I guess I'll need extra modules/packages and some other stuff

#

Thanks in advance

slate swan
#

use on_member_join events and use pillow to make those images

#

!pip pillow

unkempt canyonBOT
rustic onyx
#

ty πŸ™‚

quaint epoch
#

does await disnake.VoiceClient.play(source) use await asyncio.sleep()? and if not how do i check when the bot is done playing the source?

maiden fable
unkempt canyonBOT
tidal hawk
#

Anyone know what's rate limiter for changing Voice channel name?

#

1 after every 15 minutes?

tidal hawk
#

So it means, changing the name in 5 minute intervals is okay?

maiden fable
#

Sure

tidal hawk
#

Why does guild.approximate_presence_count return None?

maiden fable
#

U got presence intent?

#

Ah u mean Invite.approx presence count?

#

!d discord.Invite.approximate_presence_count

unkempt canyonBOT
tidal hawk
final iron
#

What

slate swan
#

!d disnake.Guild.approximate_member_count

unkempt canyonBOT
quaint epoch
#

!d tracemalloc

unkempt canyonBOT
#

New in version 3.4.

Source code: Lib/tracemalloc.py

The tracemalloc module is a debug tool to trace memory blocks allocated by Python. It provides the following information...

quaint epoch
#

does anyone else have to do py import tracemalloc tramalloc.start() at the beginning of their code?

slate swan
#

what for

#

it just checks if something is blocking

quaint epoch
# slate swan what for

idk, without it my program just gives me some error that tells me to enable traceback in tracemalloc

final iron
#

To see the full traceback

quaint epoch
final iron
#

Happens when something isnt awaited

quaint epoch
final iron
#

You're not

quaint epoch
#

i await everything

slate swan
#

your missing something then

#

show tb

final iron
#

That error happens all the time. You're forgetting to await something

slate swan
#

^

quaint epoch
#

no i missed to await smth before, fixed it tho

#

when you make an API call, you have to await the line right?

slate swan
#

depends

#

what are you using?

quaint epoch
slate swan
#

no to make request

quaint epoch
slate swan
#

oh yes fetch is a coro

#

get isnt

quaint epoch
#

i know that

#

but it gives me errors like that anyway sometimes

slate swan
#

show tb

quaint epoch
#

no errors now, working smoothly

#

thanks stackoverflow

slate swan
#

thar error is raised whenever you don't await a coroutine

slate swan
#

Hello I’m making discord bot that scrapes tiktok api for follows on the account I am not sure the best way to scrape tiktok anyone know how

#

By doing the tracemalloc.start() you ain't fixing the issue but just suppressing the error.

slate swan
#

!e

import asyncio
async def coro():
    print("lol")

async def function():
    coro()

asyncio.run(function())
unkempt canyonBOT
#

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

001 | <string>:6: RuntimeWarning: coroutine 'coro' was never awaited
002 | RuntimeWarning: Enable tracemalloc to get the object allocation traceback
slate swan
#

lol

slate swan
quaint epoch
final iron
slate swan
quaint epoch
slate swan
#

most social medias have rest apis

slate swan
quaint epoch
#

do they know abt it?

#

did you try googling tiktok api

final iron
slate swan
quaint epoch
#

alr kinda sussy baka but i'll allow it

slate swan
#

Well tiktok's banned in my country so I have no idea about its API

quaint epoch
slate swan
quaint epoch
#

idk the tiktok api, don't use tiktok but stack should help

#

anyway gtg cya

slate swan
slate swan
#

the tiktok api lol

slate swan
#

yw

#

@slate swan I think unofficial tiktok package will work better tbh

slate swan
#

I was gonna use selium but I don’t think it would work well

#

just make a wrapper for the api

#

like me with the twitter apiπŸ‘€

#

O

#

I’m not good with wrappers

#

So I’ll just use ones available to me

#

lol

#

Actually I got better idea

#

@slate swan low-key smart bc less work

#

Bc website scrapes data for me

#

ig so

blazing beacon
#

how do i get the last 10 members who sent a message in a channel( also i havent used discord.py in a while so be kind ;-;)

tidal hawk
#

Iterate through channel* history and append 10 members into a list

blazing beacon
#

using get channel history?

tidal hawk
manic wing
# blazing beacon how do i get the last 10 members who sent a message in a channel( also i havent ...

Good question, and theres not an easy method to do it as far as I am aware. This method may take a while;

How to:
You will need an instance of discord.TextChannel - I will call it channel here

-> You’re going to want to iterate through channel.history (or use the .flatten() method which I will demonstrate here.
-> You will need to iterate through a large amount of messages in case a couple people have been texting for a while - ill use 1000 messages; bearing in mind it will only take as long as it takes to find the 10 members, and if there are only 3 members who have sent messages it will take a long time and then return nothing

messages = await channel.history(limit=1000).flatten() # this holds a list of the last 1000 messages
members = []
for msg in messages:
     if msg.author not in members:
         members.append(msg.author)
        if len(members) == 10: return
``` once it has finished iterating, `members` will contain the members (instance of `discord.Member`)
blazing beacon
#

OH WHAT

slate swan
#

caeden with the help thopithink

tidal hawk
#

Sweaty answer

blazing beacon
#

omg tysm like damn πŸ’€

slate swan
blazing beacon
tidal hawk
#

& sweaty

slate swan
#

love caeden hes the goat

blazing beacon
#

im gonna modify some of the code but thanks so much @manic wing

stone moon
#

how can i assign the display roles above everyone permission to a role

how do i fetch the message link of a message

manic wing
#

ask all your questions now, ill be banned soon probably

blazing beacon
#

why though

slate swan
#

πŸ‘€

manic wing
stone moon
#

bro.

blazing beacon
stone moon
#

if u go to roles settings in display

#

how do i assign it to arole

manic wing
blazing beacon
#

that 1 is me

#

because in your code it says is message.author not in members append it

manic wing
#

did it stop early?

tidal hawk
#

Did you use it on correct channel?

blazing beacon
blazing beacon
manic wing
#

ill try

blazing beacon
#

although i did reduce the message get size to 100

#

but that still shouldnt have affected anything

#

wait do i need some o auth scope?

manic wing
wild comet
#

how would i go about turning 120000 seconds into like days, hours, minutes, seconds

blazing beacon
wild comet
#

aight

#

lemme see

blazing beacon
manic wing
#

try printing msg

#

print is a useful debugger

#

you can figure out where shit goes wrong

blazing beacon
#

doing it

wild comet
#

ok i can not figure that outw

#

what in the world

manic wing
#

dude took it seriously 😒

blazing beacon
#

odd

#

it works?

manic wing
manic wing
blazing beacon
#

hmmm

wild comet
#

what

#

i know that but then i just couldnt figure out how to do it to the rest

tidal hawk
#
messages = await ctx.channel.history(limit=100).flatten()
message_authors = list(dict.fromkeys([message.author.name for message in messages]))
authors = message_authors[:10]  # first 10 authors``` This worked for me @blazing beacon
blazing beacon
#

thank you!

tidal hawk
#
@commands.command()
    async def member_count(self, ctx):
        await ctx.send(list(dict.fromkeys([message.author.name for message in await ctx.channel.history(limit=100).flatten()]))[:10])
``` little bit better
slate swan
#

what is that indentation

tidal hawk
#
@commands.command()
async def member_count(self, ctx):
    await ctx.send(embed=disnake.Embed(title='Last 10 members', description='\n'.join(list(dict.fromkeys([message.author.name for message in 
await ctx.channel.history(limit=100).flatten()])))[:10], colour=disnake.Colour.green()))
arctic wraith
#

man's trying to fit a novel on one line

cold sonnet
#

then he should put await ctx.message.channel.history

slate swan
#

guys what is that?

tidal hawk
#

Gateaway connection error ig

slate swan
#

what can i do about it?

tidal hawk
#

It happens every time you run it?

slate swan
#

only when the loop calls this line

flat solstice
#

So I'm getting this errorpy Ignoring exception in on_message Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 343, in _run_event await coro(*args, **kwargs) File "/home/modmail/cogs/events.py", line 487, in on_message if message.author.has_any_role(data[3]) or message.author.has_guild_permissions(self.bot.config.moderator_permissions): AttributeError: 'Member' object has no attribute 'has_any_role'and I'm not too sure why, ik has_any_role exists bc I found it in the docs so maybe it's something wrong with what I'm providing it? I'm giving data[3]an array of roles from my db

tidal hawk
#

Member object doesn't have has_any_role

#

Are you trying to check, if a user has a certain role?

cold sonnet
#

obviously

tidal hawk
#

He could try if role in member.roles

cold sonnet
#

or decorators

#

commands.has_any_role

#

commands.has_guild_permissions

flat solstice
cold sonnet
cold sonnet
#

what

#

it's perfect

slate swan
#

yeah its discord

tidal hawk
#

All my bots look like it

slate swan
#

say what now

cold sonnet
#

yeah it's discord

slate swan
#

lol

tidal hawk
tidal hawk
#

hold up'

#

Try this ```py
if len(set(roles) & set([role.id for role in member.roles])) > 0: print('Your role is in list')

flat solstice
tidal hawk
#

sheesh

flat solstice
# tidal hawk sheesh

so should I use this py if len(set(data[3]) & set([role.id for role in message.author.roles])) > 0: print('Your role is in list') instead of thispy if message.author.has_any_role(data[3]) or message.author.has_guild_permissions(self.bot.config.moderator_permissions):also sorry about the pings, I keep forgetting to turn them off

tidal hawk
#

If it does, then you should use it, because the other method didn't

full lily
#

don't use &, use and

tidal hawk
#

why not

#

oh

full lily
#

it's bad practice

tidal hawk
#

But it doesn't work that way

full lily
#

look here

#set([role.id for role in message.author.roles]))
set(role.id for role in message.author.roles)
#

You should be able to throw all of that into a set without the list

#

little things

tidal hawk
#

We are trying to compare two list.. right?

#

and print out the same occuring elems

full lily
#

oh im not sure I didn't read up

tidal hawk
quiet coral
#

I was reading this piece of code :

import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="uwu ")

class MyHelp(commands.HelpCommand):
    async def send_bot_help(self, mapping):
        embed = discord.Embed(title="Help")
        for cog, commands in mapping.items():
           command_signatures = [self.get_command_signature(c) for c in commands]
           if command_signatures:
                cog_name = getattr(cog, "qualified_name", "No Category")
                embed.add_field(name=cog_name, value="\n".join(command_signatures), inline=False)

        channel = self.get_destination()
        await channel.send(embed=embed)

bot.help_command = MyHelp()

I don't understand what a command signature is can someone help?
I looked it up in the discord.py documentation it says:
Returns a POSIX-like signature useful for help command output.
what the hell is this??

slate swan
#

How do i make a mute command

tidal hawk
#

Create role which can't type/speak and then create function which adds the role to a person

slate swan
#

i tried running my python project

#

and it just plain black

#

then it closes

#

help

#

Do you have VScode?

#

ye

#

Ok

#

Open the project in VScode

#

i did

#

and when it is go to your main python file and hit f5

#

it aint running

slate swan
#

i think there is something wrong with my pc or some

#

DM me

slate swan
slate swan
flat solstice
# tidal hawk Does it work?

yeah it seems to be working, the bots responding to me again at least which it wasn't doing before when it was erroring, if I tweaked it to bepy if [len(set(data[3]) & set([role.id for role in message.author.roles])) > 0] or message.author.has_guild_permissions(self.bot.config.moderator_permissions):do you think it would still work? i'm not quite sure how to combine these two if statements correctly

arctic wraith
#

I'd change that first part to

if set(data[3]).intersection(role.id for role in message.author.roles)
#

just a bit more legible imo, other way around works too

slate swan
slate swan
#

login a discord bots token?

#

No

#

then what?

#

Like a token stealer

#

nope

#

if not then i got to report someone

#

against tos to steal tokens

#

^^

#

Welp now where do i report someone in this discord

#

Visit their website

#

Also, this isnt the right channel to discuss about it

arctic wraith
#

will it though?
[len(set(data[3]) & set([role.id for role in message.author.roles])) > 0]
will be either [True] or [False] because they wrapped it in a list

#

both of which equate to True when cast to bool, as the list isn't empty

tidal hawk
#

Bro modified my original code, now it doesn\t work

#

mine was this```py
if len(set(roles) & set([role.id for role in member.roles])) > 0: print('Your role is in list')

#

not sure why he put brackets there

slate swan
#
from bs4 import BeautifulSoup

url = "https://www.tiktok.com/@gtm"
response = requests.get(url)
soup =  BeautifulSoup(response.text, "html.parser")


follow_wrapper = soup.find(id="app")
follows = follow_wrapper.find(class_ ="tiktok-xeexlu-DivNumber e1awr0pt1")
title = follows.find(class_="followers-count")
``` idk what channel to post this so lol
#

itsa sayin 0

tidal hawk
#

Mmm bs4

#

my favorite

slate swan
#

lol

flat solstice
tidal hawk
#

if (len(set(roles) & set([role.id for role in member.roles])) > 0) or (message.author.has_guild_permissions(self.bot.config.moderator_permissions)

#

Should work

#

unless the right side is broken

flat solstice
#

oh okay, i had the weird idea that bc it was thing1 & thing2 I couldn't then make it thing1 & thing2 or thing3 without wrapping the first bit in [ ]

tidal hawk
#

xd

#

& just found the same elements from two sets

vocal snow
#

Could also use set comprehension directly: {role.id for role in member.roles}

tidal hawk
#

jep

flat solstice
tidal hawk
#

oh

#

add ) to the end of the line

flat solstice
#

πŸ‘

#

okay so next question, can someone remind how to strip list things from around my final result? (ik that probs makes no sense). My code is py await message.author.send(f'Your message had `{bad}` in it, This word is considered a "bad" word on this server so your message was removed.') but the bots sending me @SparseSpace ['b2b'] is considered a "bad" word on this server. and i can't rember how to remove the [' '] from the word, i think i need to format it or strip it right?

tidal hawk
#

can there be multiple bad words in the list? if so: ' '.join(list)

#

If there's only one for sure, then: list[0]

flat solstice
#

theoretically there could be multiple but chances are there will only be one, i'll migrate any future errors by using the first one

desert ice
#

any1 knows why this doesn't work

#

#EMBEDS
@client.command()
async def displayembed():
embed = discord.Embed(
title = 'Title',
description = 'This is a description.',
colour = discord.Colour.blue()
)

embed.set_footer(text='This is a footer.')
embed.set_image(url='https://www.google.com/search')
embed.set_thumbnail(url='https://www.google.com/search')
embed.set_author(name='Author Name', icon_url='https://www.google.com/search')
embed.add_field(name='Field Name', value='Field Value', inline=False)
embed.add_field(name='Field Name', value='Field Value', inline=True)
embed.add_field(name='Field Name', value='Field Value', inline=True)

await client.say(embed=embed)

meager chasm
#

client.say is from a very old version of discord.py

final iron
tidal hawk
#

Where do people with these ancient syntexs

final iron
#

Because they copy code from old tutorials

velvet tinsel
final iron
#

Very old tutorials

velvet tinsel
#

"welcome to another yt tutorial"

name = raw_input("name: ")
#

πŸ‘ well done

final iron
#
print "Hello to my tutorial"
velvet tinsel
#

LMAO

#
print a / b
final iron
#

Never used python 2

#

All I know is the print statement

velvet tinsel
#

I installed a python 2 lib once

#

I had to redo everything, then gave up on the first file

final iron
#

Damn

flat solstice
kindred epoch
#

how do i set an option in a slash command as Greedy?

robust rain
#

HI

#

HRU

kindred epoch
slate swan
#

Is it possible to do when a person leaves the server, it was written how long he was there?

tidal hawk
#

Replace {bad} with {" ".join(bad)}

#

@flat solstice

tidal hawk
kindred epoch
#

!d disnake.Member.joined_at

unkempt canyonBOT
#

An aware datetime object that specifies the date and time in UTC that the member joined the guild. If the member left and rejoined the guild, this will be the latest date. In certain cases, this can be None.

kindred epoch
#

@slate swan

flat solstice
# tidal hawk Replace {`bad`} with {`" ".join(bad)`}

so more like this?py await message.author.send(f'Your message had `{"".join(bad)}` in it, This word is conssidered a "bad" word on this server so your message was removed.'). also I'm now getting this error py Ignoring exception in on_message Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 343, in _run_event await coro(*args, **kwargs) File "/home/modmail/cogs/events.py", line 494, in on_message if (len(set(data[3]) & set([role.id for role in message.author.roles])) > 0) or (message.author.has_guild_permissions(self.bot.config.moderator_permissions)): AttributeError: 'Member' object has no attribute 'has_guild_permissions' so obviously something's not right with my if statement logic, one of the reasons I thought i might need to warp the thing1 & thing2 bit in [ ]

slate swan
tidal hawk
flat solstice
tidal hawk
#

Not sure bud

#

It's actually a decorator lol

flat solstice
#

okay thanks the help, guess i've gotta wade into the docs again

tidal hawk
#

Dude you can make your code 10x easier lmao

#

You could use commands.has_any_role(role.ids)

#

So it will check automatically, if the author has one of those roles

#

And then you could also add commands.bot_has_guild_permissions(**perms)

upbeat flower
# desert ice #EMBEDS @client.command() async def displayembed(): embed = discord.Embed( ...
@client.command()
async def displayembed(ctx):
  embed = discord.Embed(
    title = 'Title',
    description = 'This is a description.',
    colour = discord.Colour.blue()
  )

  embed.set_footer(text='This is a footer.')
  embed.set_image(url='https://www.google.com/search')
  embed.set_thumbnail(url='https://www.google.com/search')
  embed.set_author(name='Author Name', icon_url='https://www.google.com/search')
  embed.add_field(name='Field Name', value='Field Value', inline=False)
  embed.add_field(name='Field Name', value='Field Value', inline=True)
  embed.add_field(name='Field Name', value='Field Value', inline=True)

  await ctx.send(embed=embed)
#

try it

upbeat flower
#

his not written ctx

flat solstice
# tidal hawk You could use `commands.has_any_role(role.ids`)

i could do, if I was using a command. i'm using a on_message event since this is a auto mod thing and the event is also handling some other on message things so even if events can take decorators (i have no idea if they can or not) I couldn't use the decorators anyway without making a whole new on message event for this auto mod

tidal hawk
#

Ah yeah

#

Then it's a bit difficult to find solution to that

tidal hawk
tidal hawk
flat solstice
tidal hawk
#

put space between " "

upbeat flower
tidal hawk
#

There's no url in pictures

zinc reef
#

If I have a subcommand setup like this, will the check from the parent command (fct) apply to the subcommand (foo)?

@commands.group(invoke_without_command=True)
@commands.is_owner()
async def fct(self, ctx):
    ...

@fct.command()
async def foo(self, ctx):
    ...
tidal hawk
#

not sure, try it

cloud dawn
zinc reef
#

alright, I'll setup a custom check with some prints, since being owner of the test server I have all permissions 😬

cloud dawn
#

Just remove your ID from the owner list or string

#

is_owner() checks for the bot owner not the server owner.

zinc reef
#

yeah I know about is_owner, wasn't sure if I could remove my ID at all

cloud dawn
karmic totem
#

@cloud dawn how are you not a helper now?

cloud dawn
tidal hawk
karmic totem
#

Like you are always helpful, active, so how have you not been "hired"

cloud dawn
zinc reef
karmic totem
#

legit 20700+ messages

cloud dawn
karmic totem
#

Well.. I would want to nominate you, and I am sure a lot of people would.

#

shit

cloud dawn
karmic totem
#

Well

#

we'll see

cloud dawn
#

Besides i don't really want to ask for 'helper' and tbf nothing much would change.

karmic totem
#

ye

cloud dawn
boreal ravine
#

you can't ask for helper

#

nobody can

velvet tinsel
boreal ravine
#

yes

#

you gotta be proficient with the language, be friendly to the community and more stuff ig

cloud dawn
#

No clue, i'm just hanging out here and help some people who got questions.

slim ibex
#

same

tacit token
#
    @commands.command()
    async def f(self, ctx, *, text: commands.clean_content = None):
        """ Press F to pay respect """
        hearts = [":heart:", ":yellow_heart:", ":green_heart:", ":blue_heart:", ":purple_heart:"]
        reason = f"for **{text}** " if text else ""
        await ctx.send(f"**{ctx.author.name}** has paid their respect {reason}{random.choice(hearts)}")```

Error:discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'builtin_function_or_method' object has no attribute 'choice'
cloud dawn
karmic totem
tacit token
#

no im not

cloud dawn
tacit token
#

im not, jst import random and yeah. this code

#

so far it has worked, for some reason the commands have not worked for 2 days

karmic totem
#

Can you show us your whole code?

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

karmic totem
#

damn I was just about to

tacit token
#

this code is about 3000 lines

karmic totem
cloud dawn
karmic totem
#

and I am stalling from doing hw so take as much time as you want

tacit token
#
from random import *

class fun(commands.Cog):

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

    @commands.command()
    async def f(self, ctx, *, text: commands.clean_content = None):
        """ Press F to pay respect """
        hearts = [":heart:", ":yellow_heart:", ":green_heart:", ":blue_heart:", ":purple_heart:"]
        reason = f"for **{text}** " if text else ""
        await ctx.send(f"**{ctx.author.name}** has paid their respect {reason}{random.choice(hearts)}")

That's the top of the code.
It was not defined anywhere.

cloud dawn
#

{choice(hearts)}

karmic totem
#

oh

cloud dawn
#

You import everything

#

!e ```py
from random import *

print(choice(range(10)))

unkempt canyonBOT
#

@cloud dawn :white_check_mark: Your eval job has completed with return code 0.

4
karmic totem
#

but if you change it to import random

tacit token
#

omg ty

cloud dawn
karmic totem
#

ye ig

cloud dawn
#

But for standard libs or if you are really familiar with it it's fine.

karmic totem
#

!e py import random print(random.choice(1,2,3)) print("vs") from random import * print(choice(1,2,3))

unkempt canyonBOT
#

@karmic totem :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | TypeError: Random.choice() takes 2 positional arguments but 4 were given
karmic totem
#

ahah

#

forgot the []

cloud dawn
#
from random import (
    choice as randchoice,
    randint
    )
#

If you really want it shorter but do keep it clear what you are doing.

left crater
#

how do i make a guild

boreal ravine
#

!d discord.ext.commands.Bot.create_guild

unkempt canyonBOT
#

await create_guild(*, name, region=<VoiceRegion.us_west: 'us-west'>, icon=..., code=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").

Bot accounts in more than 10 guilds are not allowed to create guilds.
slate swan
flat solstice
#

i don't know what I'm doing wrong but this command just doesn't seem to be working and I don't seem to be getting any errorspy @commands.has_permissions(administrator = True) @commands.guild_only() @commands.command(description = "Sets the bad words that aren't allowed to said on the server..") async def badwords(self, ctx, *, words: str): data = await self.bot.get_data(ctx.guild.id) print(f"Input: {words}") bad_words = [] bad_words.append(data[28]) for word in words: bad_words.append(word) print(f"Bad Words: {bad_words}") async with self.bot.pool.acquire() as conn: await conn.execute("UPDATE data SET badwords=$1 WHERE guild=$2", [word for word in bad_words], ctx.guild.id,) await ctx.send(embed = discord.Embed(description = f"The bad words list has been update to be `{', '.join(data[28])}`.", colour = self.bot.primary_colour))

slate swan
#

When you type the command what does it say?

flat solstice
#

nothing, it just doesn't respond and it also isn't printing me any error's

#

but it's responding to other commands

slate swan
#

When you type it does something pop up on the console from where ur hosting ur bot

flat solstice
#

nope

paper snow
#

Does hikari have a method to see if a user is pinging themselves in a message? Like when I ping @paper snow (me). I tried comparing the event.author.mention to the mention string in the message, but '@paper snow' and '@paper snow' are not the same.

flat solstice
#

and the command i'm using is ,badwords act2 b2b "act 2" "act 2 b2b" glitch

flat solstice
# full lily are your prints printing?

nope 😭 I'm thinking it could be related to this error with one of my on_message events but I'm not sure why it would be, only reason I think it might be related is whenver I've had issues with on_message events in the past it's always locked up my bot but it's not locking up the bot this time, only this one command. the error on the on_message ispy Ignoring exception in on_message Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 343, in _run_event await coro(*args, **kwargs) File "/home/modmail/cogs/events.py", line 485, in on_message data = await self.bot.get_data(message.guild.id) AttributeError: 'NoneType' object has no attribute 'id'

magic ore
#

message.guild is None if the message was sent in direct messages

#

you want to check for that before accessing its id attribute

flat solstice
final iron
#

!d discord.Message.channel

unkempt canyonBOT
magic ore
#

better to just check if message.guild is None

#

and no that wouldn't work how you're doing it

flat solstice
#

okay well that fixes my on_message errors but I'm still not getting a response from this commandpy @commands.has_permissions(administrator = True) @commands.guild_only() @commands.command(description = "Sets the bad words that aren't allowed to be said on the server.") async def badwords(self, ctx, *, words: str): data = await self.bot.get_data(ctx.guild.id) print(f"Input: {words}") bad_words = [] bad_words.append(data[28]) for word in words: bad_words.append(word) print(f"Bad Words: {bad_words}") async with self.bot.pool.acquire() as conn: await conn.execute("UPDATE data SET badwords=$1 WHERE guild=$2", [word for word in bad_words], ctx.guild.id,) await ctx.send(embed = discord.Embed(description = f"The bad words list has been update to be `{', '.join(data[28])}`.", colour = self.bot.primary_colour))which as far as I can tell should be working with this command ,badwords act2 b2b "act 2" "act 2 b2b" glitch

dry kelp
#
    @commands.command()
    async def ping(self, ctx: commands.Context):

        start_time = time.time()
        message = await ctx.send("Loading ping ![typing](https://cdn.discordapp.com/emojis/937126003266957362.webp?size=128 "typing")")
        end_time = time.time()

        if round(self.angel.latency * 1000) <= 30:
            emoji = "![DotGreen](https://cdn.discordapp.com/emojis/938209006026117200.webp?size=128 "DotGreen")"
        elif round(self.angel.latency * 1000) >= 31:
            emoji = "![DotOrange](https://cdn.discordapp.com/emojis/938209047562305566.webp?size=128 "DotOrange")"    
        elif round(self.angel.latency * 1000) > 100:
            emoji = "![DotRed](https://cdn.discordapp.com/emojis/938209027849084989.webp?size=128 "DotRed")"

        if round((end_time - start_time) * 1000) <= 300:
            emoji2 = "![DotGreen](https://cdn.discordapp.com/emojis/938209006026117200.webp?size=128 "DotGreen")"
        elif round((end_time - start_time) * 1000) >= 301:
            emoji2 = "![DotOrange](https://cdn.discordapp.com/emojis/938209047562305566.webp?size=128 "DotOrange")"    
        elif round((end_time - start_time) * 1000) > 1000:
            emoji2 = "![DotRed](https://cdn.discordapp.com/emojis/938209027849084989.webp?size=128 "DotRed")"
            
        em = discord.Embed(description = f'{emoji} Bot Latency: {round(self.angel.latency * 1000)} ms\n{emoji2} API latency: {round((end_time - start_time) * 1000)} ms', color=discord.Color.from_rgb(black1, black2, black3))
        em.set_author(name="Pong")
        await message.edit(embed=em)

#

why if it's over 1000/100 it wont display the red dot?

#

it looks like it stops at the orange dot

#

should be red

spark wigeon
#

why isnt this command working?

#
async def stats(ctx):
    NoBotsMemberCount = len([m for m in ctx.guild.members if not m.bot])
    BotsMemberCount = len(ctx.guild.members) - len([m for m in ctx.guild.members if not m.bot])

    stat_em = discord.Embed(title=f"{ctx.guild}'s Stats:", colour=0x2c1945)
    stat_em.add_field(name="Member Count:", value=f"{NoBotsMemberCount} Members", inline=False)
    stat_em.add_field(name="Bot Count:", value=f"{BotsMemberCount} Members", inline=False)
    stat_em.add_field(name="Channel/Category Count:", value=f"{len(ctx.guild.channels)} Channels", inline=False)
    stat_em.add_field(name="Boosts:", value=f"{str(ctx.guild.premium_subscription_count)} Boosts", inline=False)
    stat_em.set_footer(text="https://github.com/zoaq1")

    await ctx.message.channel.send(f"{ctx.message.author.mention}", embed=stat_em)```
final iron
#

Also check out pep8

#

Variables should be named in snake_case

spark wigeon
#

too bad

final iron
#

Why are people so opposed to making semi readable code

spark wigeon
#

fine

slate swan
final iron
#

their

slate swan
#

?

final iron
#

Nice edit

#

Hows the api wrapper going

slate swan
#

pretty good

#

cache is good ratelimit is good need to add more endpoints

final iron
#

Oh the github is empty

slate swan
#

yes😳

#

ill add it when it has more endpoints or not

slate swan
#

if i do an on_message(message): and take that message variable and send the whole thing through a webhook? how can i do that if i even can?

left crater
#

how do i make my mute command ignore the bot

#

can i do something like this if member ==bot.get_user(bot_id): await ctx.send('cannot mute the bot')

bold surge
#

well the pep8 in that code is terrible but yea

#

just make sure to return the message so the command stops at that

cloud dawn
#
if member.id == bot.user.id:
    return await ctx.send('Cannot mute the bot')
left crater
#

ok thanks

spark wigeon
#

if someone sends a link in a channel, anyway to extract the link from the message into a string?

slate swan
#

yes

#

just split the string on the start of the url lol

spark wigeon
#

and end

#

but that sounds hard, may i have an example

left crater
#

just use message.content

cloud dawn
#

Best is to use regex for this

slate swan
#
s = message.content
for y in s.split(β€˜ β€˜):
    if y.startswith(β€œhttp”):
       print(y)
#

that should get the job done

cloud dawn
#

!e ```py
import re

url_regex = re.compile("http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+")
sample_text = "haha check this out https://google.com lol"

if res := re.search(url_regex, sample_text):
print(res.group(0))

unkempt canyonBOT
#

@cloud dawn :white_check_mark: Your eval job has completed with return code 0.

https://google.com
slate swan
#

that works better ^

cloud dawn
slate swan
#

@cloud dawn your right, it was just a way to get it done

slate swan
cloud dawn
#

They send json like data iirc

slate swan
#

😦 off to filtering and extracting data i go

cloud dawn
slate swan
slate swan
#

!e

print("stringhttps://www.youtube.com/".split('https', 1)[1].split('.com/', 1))
unkempt canyonBOT
#

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

['://www.youtube', '']
slate swan
slate swan
#

panda is probably the god of regex

slate swan
cloud dawn
cloud dawn
slate swan
cloud dawn
# slate swan where
_^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)*(?:\.(?:[a-z\x{00a1}-\x{ffff}]{2,})))(?::\d{2,5})?(?:/[^\s]*)?$_iuS
cloud dawn
#

Mine is shit compared to this lol

slate swan
#

lmaoo

cloud dawn
#

pretty interesting website

#

This regex beats most build-in url checks lmfao

#
@(https?|ftp)://(-\.)?([^\s/?\.#-]+\.?)+(/[^\s]*)?$@iS
``` this one is pretty clean.
quaint forum
#

import discord
@discord.Client().event

Does this just detect when the bot is actually logged in to itself, if you know what I mean?

bold surge
#

?

#

just use on_ready function

fervent shoal
#

so i recently added the snipe command, and now no other command is working

#

the snipe command works fine, but the others dont, and no error message either

slate swan
#

make it a listener

fervent shoal
#

pardon?

slate swan
#

from

@client.event

turn it to

@client.listen()
flat solstice
#

Can anyone find any error's in this code? I'm not seeing anything wrong here but my bot's not responding to the command and I'm not getting any error's or print outs and it's really confusing mepy @commands.has_permissions(administrator = True) #@commands.guild_only() @commands.command(description = "Sets the bad words that aren't allowed to be said on the server.") async def badwords(self, ctx, *, words: str): data = await self.bot.get_data(ctx.guild.id) print(f"Input: {words}") bad_words = [] bad_words.append(data[28]) for word in words: bad_words.append(word) print(f"Bad Words: {bad_words}") async with self.bot.pool.acquire() as conn: await conn.execute("UPDATE data SET badwords=$1 WHERE guild=$2", [word for word in bad_words], ctx.guild.id,) await ctx.send(embed = discord.Embed(description = f"The bad words list has been update to be `{', '.join(data[28])}`.", colour = self.bot.primary_colour))but the bot is responding fine to other commands

fervent shoal
slate swan
#

yw

fervent shoal
glacial zealot
#

It’s a Bot only method

fervent shoal
#

?

slate swan
glacial zealot
# fervent shoal ?

You probably meant to do @bot.listen(). Don’t use client and bot in the same file

fervent shoal
#

thanks

slate swan
#

no need for client when Bot is a subclass of the client class

#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

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

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

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

This class is a subclass of discord.Client and as a result anything that you can do with a discord.Client you can do with this bot.

onyx viper
# fervent shoal

the commands extension is there for a reason, use it
if you really don't want to, you need to bot.process_commands(message)

slate swan
#

no

onyx viper
#

!d discord.ext.commands.Bot.process_commands

unkempt canyonBOT
#

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

This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.

By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.

This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").

This also checks if the message’s author is a bot and doesn’t call [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.
slate swan
#

a listener is better

#

so you wont need to process it

onyx viper
#

actually, the commands extension is better

fervent shoal
#

anything to change here or no

onyx viper
#

no

fervent shoal
#

cuz its still not working

slate swan
#

show all your code

#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

fervent shoal
#

ive pasted

#

it

slate swan
#

send the url

fervent shoal
#

do i put the link her

slate swan
#

yes

fervent shoal
#

uh

slate swan
#

no your link

fervent shoal
#

that is my link

slate swan
#

its not

fervent shoal
#

nothing else ther

slate swan
#

you have to add the code and press the save button

onyx viper
#

there should be a id at the end of the link

fervent shoal
slate swan
#

yes

#

remove your client

#

only use the Bot class

onyx viper
#

you haven't changed this?

fervent shoal
#

the snipe command works

slate swan
#

remove client

#

and use the class

fervent shoal
#

huh

onyx viper
#

why are you instantiating two different bots

slate swan
#

remove client

fervent shoal
#

change client to bot

slate swan
#

no remove the whole client var

onyx viper
#

and replace all instances of client with bot

fervent shoal
#

which line is it

onyx viper
#

17

slate swan
#

on top?

fervent shoal
#

you mean 18? or am i looking atthe wrong place

onyx viper
#

yeah 18

slate swan
#

yes 18

onyx viper
#

it's 17 on the haste πŸ˜•

fervent shoal
#

remove it?

slate swan
#

yes

fervent shoal
#

done

#

anything else?

slate swan
#

and make all the instances to bot

fervent shoal
#

also done

onyx viper
#

and change line 81 to @bot.listen()

fervent shoal
#

this to bot as well?

slate swan
#

yes

#

only have your bot constructor

#

and make all events to listeners

fervent shoal
#

remove it or delete

slate swan
#

its the same thing?

fervent shoal
#

so i remove it

onyx viper
#

and i'd highly recommend using the commands extension because you're already using commands.Bot
don't go through the pain of using on_message commands

fervent shoal
#

so that would be?

#

says line 51 has errpr

slate swan
#

!traceback

unkempt canyonBOT
#

Please provide the full traceback for your exception in order to help us identify your issue.

A full traceback could look like:

Traceback (most recent call last):
    File "tiny", line 3, in
        do_something()
    File "tiny", line 2, in do_something
        a = 6 / b
ZeroDivisionError: division by zero

The best way to read your traceback is bottom to top.

β€’ Identify the exception raised (in this case ZeroDivisionError)
β€’ Make note of the line number (in this case 2), and navigate there in your program.
β€’ Try to understand why the error occurred (in this case because b is 0).

To read more about exceptions and errors, please refer to the PyDis Wiki or the official Python tutorial.

fervent shoal
#

how do i fix this

slate swan
#

send the tb

fervent shoal
#

pardon?

onyx viper
#

send the whole traceback

fervent shoal
#

in terminal?

slate swan
#

yes

#

where else would you get your traceback?

fervent shoal
#

Traceback (most recent call last):
File "C:\Users*my name\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\my name\riotbot #3.py", line 51, in on_message
msg = sys.argv[1].split(",")
IndexError: list index out of range

onyx viper
#

sys.argv doesn't have a second item

slate swan
#

!e

a = ["lol"]
print(a[1])
unkempt canyonBOT
#

@slate swan :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | IndexError: list index out of range
slate swan
#

you cant index something that doesnt have such an element

fervent shoal
#

how would i fix that

onyx viper
#

provide something to argv

#

!d sys.argv

unkempt canyonBOT
#

sys.argv```
The list of command line arguments passed to a Python script. `argv[0]` is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the [`-c`](https://docs.python.org/3/using/cmdline.html#cmdoption-c) command line option to the interpreter, `argv[0]` is set to the string `'-c'`. If no script name was passed to the Python interpreter, `argv[0]` is the empty string.

To loop over the standard input, or the list of files given on the command line, see the [`fileinput`](https://docs.python.org/3/library/fileinput.html#module-fileinput "fileinput: Loop over standard input or a list of files.") module.

See also [`sys.orig_argv`](https://docs.python.org/3/library/sys.html#sys.orig_argv "sys.orig_argv").

Note

On Unix, command line arguments are passed by bytes from OS. Python decodes them with filesystem encoding and β€œsurrogateescape” error handler. When you need original bytes, you can get it by `[os.fsencode(arg) for arg in sys.argv]`.
slate swan
#

remember that python counts from 0

fervent shoal
#

uhuh

onyx viper
#

how did you run your script

#

you're probably missing command line arguments

slate swan
#

!e

example_list = [1, 2, 3, 4, 5]
print(example_list[0])
fervent shoal
#

run without debug

#

is that what u mean

unkempt canyonBOT
#

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

1
onyx viper
fervent shoal
#

i didnt type it out into termial

#

typed it out in discord

#

cuz this a discord bot

onyx viper
#

you need to somehow run the bot

#

either through your IDE or through terminal

fervent shoal
#

it detects the messages

onyx viper
#

what command did you use (e.g. python3 main.py) to start the script?

slate swan
#

not only that

fervent shoal
#

shows up in terminal

slate swan
#

why even use sys?

#

i see no command that needs it

onyx viper
#

to retrieve command line arguments

fervent shoal
#

how would i make this better then

slate swan
#

just why

#

if you want to get args of a command just print them?

#

im not sure what you want

fervent shoal
#

the bot to respond to the command

#

which it did earlier, jus not sure why not now

slate swan
#

then why have it?

onyx viper
#

sys.argv retrieves arguments when you run it through terminal, for example python3 main.py 1 2 3 would make sys.argv ["1", "2", "3"]

#

you can't get the user's timezone

#

yes

slate swan
#

an argument?

#

just make a converter

fervent shoal
onyx viper
# fervent shoal says line 51 has errpr

you need to pass arguments while running your script to populate sys.argv
for example python3 main.py 1 2 3
i don't even get why you are using sys.argv here

fervent shoal
#

would i remove it

onyx viper
#

you can remove it

#

not sure what that piece of code is doing anyways

fervent shoal
#

that line has been removed, anything else?

onyx viper
#

that whole listener is messed up, cause msg and regexGroups isn't defined
don't know what you want msg and regexGroups to be, so you need to somehow define it

fervent shoal
#

would i delete that entire line?

onyx viper
#

delete the whole listener if you don't know what you're doing with it

#

25

fervent shoal
#

member is not defined

onyx viper
#

show traceback

fervent shoal
#

there is none

onyx viper
#

nothing we can do about it :/

fervent shoal
#

tf?

onyx viper
fervent shoal
#

shows this now

onyx viper
#

yeah it's defined, but you're not using it anywhere

fervent shoal
#

do i remove that line then?

onyx viper
#

you can

#

what is new_func for

fervent shoal
#

just showed up

onyx viper
#

wdym

fervent shoal
#

quick fix ig

onyx viper
#

for what

fervent shoal
#

the mem

onyx viper
#

the what?

fervent shoal
#

it was "mem" before

slate swan
onyx viper
#

nope