#discord-bots

1 messages · Page 526 of 1

slate swan
#

If it's a private bot heroku is 100% the go-to bc it's free and easy to set up

#

meh, slow

#

It's pretty fast

slate phoenix
#
- Bots are not what the platform is designed for. Heroku is designed to provide web servers (like Django, Flask, etc). This is why they give you a domain name and open a port on their local emulator.

- Heroku's environment is heavily containerized, making it significantly underpowered for a standard use case.

- Heroku's environment is volatile. In order to handle the insane amount of users trying to use it for their own applications, Heroku will dispose your environment every time your application dies unless you pay.

- Heroku has minimal system dependency control. If any of your Python requirements need C bindings (such as PyNaCl binding to libsodium, or lxml binding to libxml), they are unlikely to function properly, if at all, in a native environment. As such, you often need to resort to adding third-party buildpacks to facilitate otherwise normal CPython extension functionality. (This is the reason why voice doesn't work natively on heroku.)

- Heroku only offers a limited amount of time on their free programme for your applications. If you exceed this limit, which you probably will, they'll shut down your application until your free credit resets.
slate swan
#

using slash commands makes me think it's not a private bot

#

My bot is on heroku

#

not slow ¯\_(ツ)_/¯

slate swan
#

But as i said, for a private Bot heroku is good

slate phoenix
#

Google Cloud Services is better imo it doesn't cost much either

slate swan
#

You need a cc

slate phoenix
#

yes because its paid

slate swan
#

Exactly

#

Not everyone got one of those

#

while I was using heroku, I made two heroku accounts so that if one exceeds the 550h/month, I just start the app on the other account

covert igloo
#

@slate swan after putting it in the requirement file

slate swan
#

That's what I'm doing 😎

slate swan
slate phoenix
#

seems like too much hassle lol

covert igloo
slate swan
#

what did he do wrong

#

The name of the lib isn't discord_slash, check again

slate swan
unkempt canyonBOT
#
Nah.

Package could not be found.

slate swan
#

¯\_(ツ)_/¯

covert igloo
slate swan
#

mhm

#

That's the module

covert igloo
#

do you have any idea what the lib is

slate swan
#

Nope

#

Never used it

covert igloo
#

oh i see

#

its discord-py-slash-commands

slate swan
#

¯\_(ツ)_/¯

wintry panther
#

how to reject dms from a bot

#

like how to make it not respond to a dm

slate swan
#

Check if the user that dm'ed you is a bot or not

slate swan
wintry panther
#

like dont allow commands to be used if you dm the bot

slate swan
#

Oh

#

!d discord.ext.commands.guild_only

unkempt canyonBOT
#

@discord.ext.commands.guild_only()```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command.

This check raises a special exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
slate swan
#

Add that to all of your commands

hasty iron
#

or use a bot.check

slate swan
#

Or you could also simply make a bot check if you know how to

covert igloo
deft hill
#

How does one make a better help command?

I tried pretty_help but it doesnt seem to be the best/has limited customization.

slate swan
#

what's pretty_help

#

just use an embed, put a color and some fields

hasty iron
#

wow

slate swan
#

it be like that

hasty iron
slate swan
#

^

deft hill
vestal rapids
#

hey guys

#

im having a bit of a problem

#
ModuleNotFoundError: No module named 'discord'
#

does anyone know how to help with this, if so please let me know

#

i have it installed through pip and stuff but it still says this its confusing and nothing is helping no matter what i try

manic wing
#

type python -v

#

and python3 -v

vestal rapids
#

can you give me like an example?

#

im a little slow sorry

wise shell
# manic wing through pip and pip3?

Most if not all the tutorials I see use pip install but on my Ubuntu machine I had to do pip3 install. No one seems to have the same problem, though it's not really a problem. If I use a virtual environment, though, pip install works fine.

slate swan
#

!ytdl

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)
heavy heath
#

Hey, can anyone tell me why my author/thumbnail isnt working? Ive been trying to figure out why but i have no idea... Code is below.

            title=f"{twitch_username}'s Twitch Stats",
            description=f"Username: {twitch_username}\nAccount Creation: {twitch_creation_tidy}\nBan Status: {twitch_ban_stat}",
            colour=discord.Colour.green()
        )
        embed.set_author(name='Utango')
        embed.set_thumbnail(url=twitch_pfp)

        await ctx.message.channel.send(embed=twitch_stats_embed)```
#

ah i figured it out... Im dumb

delicate moat
#

Hey, so I'm trying to make an event function that sends a message to the logs channel when a message is deleted. This is the code I have so far:

import discord
from discord.ext.commands import Bot
import datetime

client = Bot(command_prefix='>')
logs_channel = client.get_channel(896464547588759603)
intent = discord.Intents.default();
intent.members = True;
intent.guilds = True;

@client.event
async def on_ready():
    print("Portfolio bot is now running.")

# On delete event filter
@client.event
async def on_message_delete(message):
  if not message.author.bot:
    embeded = discord.Embed(color = 0xEE8700)
    embeded.add_field(name = "Message has been deleted:", value=f"{message.author} has sent the following message which is now deleted:\n'{message.content}'\n\nDate: {datetime.date.today()}\nUser ID: {message.author.id}")
    await client.wait_until_ready()
    await logs_channel.send(embed = embeded)

        
client.run("token :)")
#

And it returns a Attribute Error: 'NoneType' Object has no attribute 'send'

#

Can someone tell me what I'm doing wrong?

vestal rapids
#

man i cant even import discord

slate phoenix
#

try putting logs_channel = client.get_channel(896464547588759603) inside your event

vestal rapids
#

i get the error for no module when i try to run my bot

#

ModuleNotFoundError: No module named 'discord'

delicate moat
slate phoenix
vestal rapids
#

yes i did

slate phoenix
#

what IDE are you using?

vestal rapids
#

VS

delicate moat
#

What OS are you using? Because when I tried running discord.py on my mac it wouldn't work

vestal rapids
#

windows

delicate moat
#

oh

vestal rapids
#

and it says it worked and installed

#

but when i try to run the bot it gives me the error

slate phoenix
#

try this: uninstall both modules, reinstall, restart your ide

vestal rapids
#

weird im still getting the error

slate phoenix
vestal rapids
#

yes

slate phoenix
#

do you have multiple versions of python installed?

vestal rapids
#

how do i check

#

i dont think i do im pretty sure i only have 3.10

slate phoenix
#

iirc d.py is supported up to 3.8

vestal rapids
#

so i need to uninstall 3.10 and install 3.8?

slate phoenix
#

I would yeah, i doubt thats the issue though

#

I had similar issues before and it was because i had multiple versions of python installed

reef shell
#

3.8+

vestal rapids
#

so it should work with 3.10?

reef shell
#

I saw some people are already using, i guess there should be no problems

slate phoenix
#

on the github it had this 🤷‍♂️

reef shell
solid wave
#

How do I send a message

#

like an @ message

#

with only the name of the person who sent it

reef shell
#

wdym?

solid wave
#

like I have

#

author = message.author

#

and if you print it

#

it is

#

the name of the person

#

but I want it like @solid wave

#

not just Asad

reef shell
#

then use message.author.mention

solid wave
#

Thanks

#

is it a function

reef shell
#

No?

#

!d discord.User.mention

unkempt canyonBOT
#

property mention: str```
Returns a string that allows you to mention the given user.
solid wave
#

ok thanks

reef shell
#

message.author is a discord.User or discord.Member instance

reef shell
solid wave
#

yeah

#

also one more thing

#

if someone sends a message

#

how do I make sure they have the authority

#

like if they have a certain role to do it

#

how do I get their roles

reef shell
#

i assume you are using on_message event. You need to define commands using command decorator and add checks for that

solid wave
#

Ok

#

but...

#

how do I do it?

reef shell
#

!d discord.ext.commands.command

unkempt canyonBOT
#

@discord.ext.commands.command(name=..., cls=..., **attrs)```
A decorator that transforms a function into a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or if called with [`group()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.group "discord.ext.commands.group"), [`Group`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group").

By default the `help` attribute is received automatically from the docstring of the function and is cleaned up with the use of `inspect.cleandoc`. If the docstring is `bytes`, then it is decoded into [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") using utf-8 encoding.

All checks added using the [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") & co. decorators are added into the function. There is no way to supply your own checks through this decorator.
solid wave
#

give me an example

reef shell
solid wave
#

which part tells me how to get roles

flint isle
#

i am needing some sample code that has my bot interact with a telnet server and processes the responce
here is the ip info and the port
10.0.0.1
port:8080

solid wave
#

ok

unkempt canyonBOT
#

The rules and guidelines that apply to this community can be found on our rules page. We expect all members of the community to have read and understood these.

solid wave
#

why are you asking me

#

also

#

this is the python server

hot sparrow
#

I just started doing bots with python for discord and I already got a problem.
I took this guys script form youtube and isn't working on my server...

#
@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))
async def on_message(message):
    username = str(message.author).split("#")[0]
    user_message = str(message.content)
    channel = str(message.channel.name)
    print(f'{username}: {user_message} ({channel})')
    if message.author == client.user:
        return
    if message.channel.name == 'kk':
        if user_message.lower() == 'hello':
            await message.channel.send(f'Hello {username}!')
            return
        elif user_message.lower() == 'bye':
            await message.channel.send(f'See ya {username}')
            return
        elif user_message.lower() == '!random':
            response = f'random: {random.randrange("Você conhece a piada do pônei? Pô nei eu", "O que o pagodeiro foi fazer na igreja? Cantar pá God", "O que o pato falou para a pata? Vem quá", "Você sabe qual é o rei dos queijos? O reiqueijão")}'
            await message.channel.send(response)
            return
    if user_message.lower() == '!anywhere':
        await message.channel.send('This can be used anywhere!')
        return
client.run(TOKEN)```
#

The script is logging on the bot account, but not reading or responding to messages.
What it's wrong?

patent surge
#
async def on_message(message):
    if await events.is_not_restricted_channel(message):
        if message.author == bot.user:
            return
        else:
           print("Processing")
           await bot.process_commands(message)```
Process command is not working ?
#

Can anyone help me in this?

brisk fiber
hot sparrow
brisk fiber
#

reading the docs is always a good place to start– they have examples

rich valley
#

how would I get <t:1633827472:F> to work and whats it called so I can find docs and stuff for it (someone showed me this and I have no clue whats happening but it converts to different timezones)

hot sparrow
rich valley
brisk fiber
rich valley
#

so what would I google

#

oh ok thanks

brisk fiber
#

np

#

oh wait

slate swan
#

logs = await guild.audit_logs(limit=1, target=discord.AuditLogDiff.vanity_url_code).flatten()

#

type object 'AuditLogDiff' has no attribute 'vanity_url_code'

#

How would I fix this?

mortal dove
#

Is there any way to get if a user was mentioned in a string? I'm pretty sure there is I just forgot how. Say I have '@mortal dove', it would know that @mortal dove is an instance of discord.User, from the string. Hope that makes sense? Basically it needs to take in a string or a user, and do something if it is a string and something else if it is a user.

slate swan
#

so basically within the same command, you're trying to target either a user or a string?

mortal dove
#

Yeah

slate swan
#

whats the code for your command and what are you trying to do

mortal dove
#

If it helps, it's for a purge command. You can either do 'bot' (and similar), 'user', 'all', or mention a user

#

It's kinda a lot one sec

slate swan
#

ah ok

#

lemme see what i can do

mortal dove
#

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

slate swan
mortal dove
#

Or all messages that ping jeff, or all messages by kyle

sage otter
#

iterate over it then?

mortal dove
#

Unordered, so I would be confused over more than one ping

sage otter
#

Just to make sure I’m understanding this right. You want to delete any message that has a mention of a specific user?

mortal dove
#

Well that's a possibility

#

and one that wouldn't work if I use an unordered list

slate swan
#

yeah, so he basically wants it to do that, and have it so that it's optional in which case he can just purge messages like normal

sage otter
#

Literally just

mortal dove
#

Delete Everything from Kyle that includes Jimmy != Deleted Everything from Jimmy that Includes Kyle. There's no difference in the unordered list

#

yes but

sage otter
#

Actually hold on

mortal dove
#

Im gonna use MS paint to demonstrate my point one sec

slate swan
#
    @commands.command()
    async def purge(self, ctx, user: discord.Member = None, amount: int = int):
        if user == None:
            if amount == None:
                await ctx.message.channel.purge(5)
                await ctx.send(f'Purged 5 Messages!')
            else:
                await ctx.message.channel.purge(amount)
                await ctx.send(f'Purged {amount} Messages!')
        else:
            if amount == None:
                async for message in ctx.channel.history(limit = 5):
                    if message.author == user:
                        await ctx.message.channel.purge(5)
                        await ctx.send(f'Purged 5 Messages From User: {user.name}')
            else:
                async for message in ctx.channel.history(limit = amount):
                    if message.author == user:
                        await ctx.message.channel.purge(amount)
                        await ctx.send(f'Purged {amount} Messages From User: {user.name}')```
#

lmk if this is what you wanted

#

and if it works

#

i havent tested it yet lol

mortal dove
#

Hmm I think I can make it work

#

Thonx

slate swan
#

is that what you wanted?

#
py
logs = await guild.audit_logs(limit=1, target=discord.AuditLogDiff.vanity_url_code).flatten()
type object 'AuditLogDiff' has no attribute 'vanity_url_code'```
How would I fix this?
#
    @commands.command()
    async def purge(self, ctx, user: discord.Member = None, amount: int = int):
        if user == None:
            if amount == None:
                await ctx.message.channel.purge(5)
                await ctx.send(f'Purged 5 Messages!')
            else:
                await ctx.message.channel.purge(amount)
                await ctx.send(f'Purged {amount} Messages!')
        else:
            if amount == None:
                async for message in ctx.channel.history(limit = 5):
                    if message.author == user:
                        await ctx.message.channel.purge(5)
                        await ctx.send(f'Purged 5 Messages From User: {user.name}')
            else:
                async for message in ctx.channel.history(limit = amount):
                    if message.author == user:
                        await ctx.message.channel.purge(amount)
                        await ctx.send(f'Purged {amount} Messages From User: {user.name}')```
#

wait i fixed it a bit @mortal dove

#

i messed up with the ctx.author

sage otter
#

This only solves like 1/2 of the guys problem tho. He said he wanted to purge messages that were by that specific author and that included a specific mention of someone.

slate swan
sage otter
#

and that included a specific mention of someone.

slate swan
#

oh basically if that persons name was mentioned inside of a message it would get deleted?

sage otter
#

yeah

slate swan
#

thats not bad

sage otter
#
if discord.User.mention in [x.mention for x in discord.Message.mentions]
    ...
slate swan
#
async for message in ctx.channel.history():
     if user.mention in message.content:
          await message.delete()```
#

would that work?

outer basalt
#

what is the dif btw thread remove and delete?

bright palm
patent surge
#

why my bot.process_commands(message) is not working.
There is command written but the command is not getting run

slate swan
patent surge
#

Still not working

#

😩

odd walrus
#

just to make sure, if I have my discord bot in Server A only
and someone that isnt in it will not be able to use it ln the DMS right

slate swan
#
guildid=894378876883578890

@bot.command()
async def whois(ctx,*,message:int):

    guild = bot.get_guild(guildid)

    whoisuser = guild.get_member(message)
    await ctx.send(f"**{message}** is **{whoisuser}**")
    print(f"**{message}** is **{whoisuser}**")```
how would i make this get_member from all the guilds it's in
odd walrus
#

Uhm i think theres some author thingy u can use

#

So you dont need to do the whoisuser stuff

odd walrus
zenith hare
#

is it possible to know with which invitation code a member enter? ,':

odd walrus
#

i think dyno has a feature that can track

#

Not sure tho

zenith hare
odd walrus
#
@bot.event
async def on_member_join(member):

    # Getting the invites before the user joining
    # from our cache for this specific guild

    invites_before_join = invites[member.guild.id]

    # Getting the invites after the user joining
    # so we can compare it with the first one, and
    # see which invite uses number increased

    invites_after_join = await member.guild.invites()

    # Loops for each invite we have for the guild
    # the user joined.

    for invite in invites_before_join:

        # Now, we're using the function we created just
        # before to check which invite count is bigger
        # than it was before the user joined.
        
        if invite.uses < find_invite_by_code(invites_after_join, invite.code).uses:
            
            # Now that we found which link was used,
            # we will print a couple things in our console:
            # the name, invite code used the the person
            # who created the invite code, or the inviter.
            
            print(f"Member {member.name} Joined")
            print(f"Invite Code: {invite.code}")
            print(f"Inviter: {invite.inviter}")
            
            # We will now update our cache so it's ready
            # for the next user that joins the guild

            invites[member.guild.id] = invites_after_join
            
            # We return here since we already found which 
            # one was used and there is no point in
            # looping when we already got what we wanted
            return

https://medium.com/@tonite/finding-the-invite-code-a-user-used-to-join-your-discord-server-using-discord-py-5e3734b8f21f

mortal dove
#

How do I find if a string has a mention in it without using message.mentions?

slate swan
#

'Guild' object has no attribute 'vanity_url_code'

#

what would the correct object be

#

this has me so confused

odd walrus
#

was on phone cant copy paste properly

lilac latch
#

I actually wanted to make a command like botdie which can kill the bot and botalive which can bring it back to life idk if it's possible

slate swan
#

instead of killing the bot you can suspend it, so any other commands won't work

lilac latch
#

How??

slate swan
#

one sec

lilac latch
slate swan
lilac latch
#

I don't want to write it in front of each command

slate swan
#
for command in client.commands:
  command.update(enabled=False)
``` will disable the commands
slate swan
#

is it possible to record microphone and play it at the same time on a discord bot?

boreal ravine
somber musk
#

I have a functioning bot but how can I make it when it gets pinged it says the help command

civic fractal
#

if your bot is in that list, then send the help command

slate swan
#

!d discord.ext.commands.Bot.get_command

unkempt canyonBOT
#

get_command(name)```
Get a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") from the internal list of commands.

This could also be used as a way to get aliases.

The name could be fully qualified (e.g. `'foo bar'`) will get the subcommand `bar` of the group command `foo`. If a subcommand is not found then `None` is returned just as usual.
slate swan
#

you can invoke the help command then..

calm vortex
boreal ravine
#

they asked whats the use of it

calm vortex
#

Idrk

#

So I showed what it does

#

I have seen impersonation commands that use webhooks though

#

Like making it look like someone is saying something using a webhook message

boreal ravine
#

webhooks can also hyperlink

#

no it deleted the webhook

calm vortex
#

It deletes the webhook

calm vortex
tough wagon
#

!d discord.WebhookMessage.delete

unkempt canyonBOT
#

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

Deletes the message.
tough wagon
#

for that

calm vortex
#

m is None if I do
m = await webhook.send(...)
Sad

tough wagon
#

more code?

#

and full traceback

calm vortex
#

No I don't want help, just saying something I noticed

tough wagon
#

ehm okay

slate swan
boreal osprey
slate swan
#

i need to have the guild = all the guilds the bot is in

#

how would i do that

tough wagon
#

bot?

boreal osprey
slate swan
#

okay

tough wagon
#

if a bot then it is

#

!d discord.ext.commands.Bot.guilds

unkempt canyonBOT
tough wagon
#

@slate swan

slate swan
#

ty

burnt wharf
#

How would I create buttons for a user to interact with?

tough wagon
burnt wharf
#

Would it be 2.0?

tough wagon
#

it is 1.7.3, but there is unreleased 2.0.0

burnt wharf
#

Since you're saying that 2.0 is unreleased

tough wagon
#

yes it is unreleased because some features not ready, but there is all features of 1.7.3 and views (buttons, dropdowns), ephemeral messages, banners, guild avatars and much more ready

#

because that i am using it

#

buttons are impossible in 1.7.3

burnt wharf
tough wagon
#

I don't know

#

but already about month there is nothing changed

#

it like, stopped

#

xD

slate swan
#

how can I add proxies on my python file...
like...I have a bot and it frequently gets blocked by discord api...How can I use a random proxy whenever I start the bot??

final iron
hardy geyser
#

how do I add a debounce for my discord bot?

tough wagon
#

debouce?

#

maybe description?

hardy geyser
slate swan
#

a cooldown?

hardy geyser
#

yeah basically

tough wagon
#

!d discord.ext.commands.cooldown

unkempt canyonBOT
#

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

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

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

A command can only have a single cooldown.
slate swan
#

^

gloomy quest
#

oh

hardy geyser
#

thanks

brisk fiber
dusk pumice
#

How can I send a message to all server where my bot is in?

tough wagon
#

for g in bot.guilds: send message
spam is not a good thing...

slate swan
#

!d discord.Client.guilds , gets you all guilds
choose a channel to send message in , and use channel.send

unkempt canyonBOT
#

property guilds: List[discord.guild.Guild]```
The guilds that the connected client is a member of.
slate swan
#

why would you want to do that though?

dusk pumice
#

I want to tell the server the update of my bot

tough wagon
#

lol ok

dusk pumice
#

Plz

tough wagon
#
for g in bot.guilds:
    await g.system_channel.send('HeY, ThErE iS a NeW uPdAtE oF mE')```
dusk pumice
#

HeY, ThErE iS a NeW uPdAtE oF mE?!?!!? lol

tough wagon
#

🙂

calm vortex
dusk pumice
slate swan
#

you can still use forks if you need slash cmds... ( disnake , pycord etc)

steep estuary
#

why slash commands are not working?

dusk pumice
#

I know like that

steep estuary
#

okk

dusk pumice
steep estuary
#

:/

dusk pumice
#
@slash.slash(name="test", guild_ids=[])

try like this

#

@steep estuary

steep estuary
#

i tried this

#

it didn't worked :/

dusk pumice
#

Did you imported ```python
from discord_slash import SlashCommand

steep estuary
#

did :/

dusk pumice
#

this?

#

hmm

steep estuary
#

ctx: SlashContext ?

#

this is necessary?

#

wht?

dusk pumice
#

Ctx is context

steep estuary
#

yes but i saw docs

sweet merlin
#

how do i get channel id? like message.content.id

dusk pumice
#

So I guess it's not that important

sweet merlin
steep estuary
dusk pumice
#

or message

sweet merlin
#

im using cogs

#

and listener

dusk pumice
tough wagon
#

doesn't metter just get channel from object that have this attr

#

message for example

dusk pumice
sweet merlin
#

thanks

dusk pumice
#

🙂

sweet merlin
#

uh its getting the channel id?

dusk pumice
#

Yes

sweet merlin
dusk pumice
#

Ok

slate swan
#

Replace channel with message

dusk pumice
#

yea

unkempt canyonBOT
sweet merlin
#

ok

dusk pumice
#
@bot.command()
async def msg(ctx):
    print(ctx.message.id)
solar pike
#

how can we build our own api?

slate swan
#

Use a web framework that makes APIs or simply create basic raw PHP or similar files and host it on a web server

solar pike
#

oh ok

slate swan
#

Depending on the language(s) you know there is definitely a framework to make web applications, just search it up

dusk pumice
# sweet merlin ok

Or try this. you will see everything of message.

@bot.event
async def on_message(msg)
    print(msg)

Haha. It's not useful. but if it's test bot..

sweet merlin
#

ok

dusk pumice
#

Than you get a message like

 <Message id=896630045731336233 channel=<TextChannel id=888569645047636002 name='일반' position=0 nsfw=False news=False category_id=888569645047636000> type=<MessageType.default: 0> author=<Member id=853955303535804436 name='이도열' discriminator='5785' bot=False nick=None guild=<Guild id=||Private!|| name='||Private!||' shard_id=None chunked=False member_count=4>> flags=<MessageFlags value=0>>
tough wagon
dusk pumice
#

yep. I just copied the console

tough wagon
#

okay that's true

patent surge
#
        """Handling errors"""
        if isinstance(error, commands.CommandNotFound):
            print("Ignoring one Command not found error.")
        elif isinstance(error, commands.MissingRequiredArgument):
            await ctx.send("Please give all the required arguments.")
        elif isinstance(error, commands.MissingPermissions):
            await ctx.send("Please give me all permissions.\nsend message, embed links, attach files")
        else:
            print(f"ERROR: {error}")
            raise error```
What is the problem in raise error?
dusk pumice
tough wagon
dusk pumice
#

XD

#

Hmm

#

idk

tough wagon
slate swan
#
message = embedesc 
        if "{user.id}" in message:
                    message = message.replace("{user.id}", "%s" % (user.id))

        if "{user.mention}" in message:
                message = message.replace("{user.mention}", "%s" % (user.mention))

        if "{user.tag}" in message:
                message = message.replace("{user.tag}", "%s" % (user.discriminator))

        if "{user.name}" in message:
                message = message.replace("{user.name}", "%s" % (user.name))

        if "{server.name}" in message:
                message = message.replace("{server.name}", "%s" % (user.guild.name))
                
        if "{server.membercount}" in message:
                message = message.replace("{server.membercount}", "%s" % (user.guild.member_count))
        try:
            embed = discord.Embed(title=embedtitle,description=embedesc)
            embed.set_footer(text=embedfooter)
            await channel.send(embed=embed)
            await ctx.reply('Completed! **Welcome Events** were tested!')
        except:
            await ctx.reply("Failed! **Welcome Events** were not tested")
slate swan
#

variables will not set

slate swan
#

!e
message = embedesc
if "{user.id}" in message:
message = message.replace("{user.id}", "%s" % (user.id))

    if "{user.mention}" in message:
            message = message.replace("{user.mention}", "%s" % (user.mention))

    if "{user.tag}" in message:
            message = message.replace("{user.tag}", "%s" % (user.discriminator))

    if "{user.name}" in message:
            message = message.replace("{user.name}", "%s" % (user.name))

    if "{server.name}" in message:
            message = message.replace("{server.name}", "%s" % (user.guild.name))
            
    if "{server.membercount}" in message:
            message = message.replace("{server.membercount}", "%s" % (user.guild.member_count))
    try:
        embed = discord.Embed(title=embedtitle,description=embedesc)
        embed.set_footer(text=embedfooter)
        await channel.send(embed=embed)
        await ctx.reply('Completed! **Welcome Events** were tested!')
    except:
        await ctx.reply("Failed! **Welcome Events** were not tested")
#

bruh

patent surge
#

No need of doing raise error()

tough wagon
tough wagon
patent surge
slate swan
tough wagon
slate swan
#
user = ctx.author
        message = embedesc 
        if "{user.id}" in message:
                    message = message.replace("{user.id}", "%s" % (user.id))

        if "{user.mention}" in message:
                message = message.replace("{user.mention}", "%s" % (user.mention))

        if "{user.tag}" in message:
                message = message.replace("{user.tag}", "%s" % (user.discriminator))

        if "{user.name}" in message:
                message = message.replace("{user.name}", "%s" % (user.name))

        if "{server.name}" in message:
                message = message.replace("{server.name}", "%s" % (user.guild.name))
                
        if "{server.membercount}" in message:
                message = message.replace("{server.membercount}", "%s" % (user.guild.member_count))
        try:
            embed = discord.Embed(title=embedtitle,description=embedesc)
            embed.set_footer(text=embedfooter)
            await channel.send(embed=embed)
            await ctx.reply('Completed! **Welcome Events** were tested!')
        except:
            await ctx.reply("Failed! **Welcome Events** were not tested")
#

explain hwow that doesnt work

#

and its not indentation

dusk pumice
slate swan
#

you miss f

#

it should be py if f"{user.id}" in message: and so on

#

..

tough wagon
# slate swan ```py user = ctx.author message = embedesc if "{user.id}" in me...
        user = ctx.author
        message = embedesc 
        message = message\
        .replace("{user.id}", user.id)\
        .replace("{user.mention}", user.mention)\
        .replace("{user.tag}", user.discriminator)\
        .replace("{user.name}", user.name)\
        .replace("{server.name}", user.guild.name)\
        .replace("{server.membercount}", user.guild.member_count)
        try:
            embed = discord.Embed(title=embedtitle,description=message)
            embed.set_footer(text=embedfooter)
            await channel.send(embed=embed)
            await ctx.reply('Completed! **Welcome Events** were tested!')
        except:
            await ctx.reply("Failed! **Welcome Events** were not tested")```
dusk pumice
slate swan
#

bro what

tough wagon
slate swan
#

yes

tough wagon
#

what?

slate swan
#

the variable wont set

tough wagon
#

wdym?

slate swan
#

it still says {user.id}

tough wagon
#

oh, i know why

dusk pumice
#
        message = embedesc 
        if user.id in message:
                    message = message.replace("{user.id}", "%s" % (user.id))

        if user.mention in message:
                message = message.replace("{user.mention}", "%s" % (user.mention))

        if user.tag in message:
                message = message.replace("{user.tag}", "%s" % (user.discriminator))

        if user.name in message:
                message = message.replace("{user.name}", "%s" % (user.name))

        if server.name in message:
                message = message.replace("{server.name}", "%s" % (user.guild.name))
                
        if server.membercount in message:
                message = message.replace("{server.membercount}", "%s" % (user.guild.member_count))
        try:
            embed = discord.Embed(title=embedtitle,description=embedesc)
            embed.set_footer(text=embedfooter)
            await channel.send(embed=embed)
            await ctx.reply('Completed! **Welcome Events** were tested!')
        except:
            await ctx.reply("Failed! **Welcome Events** were not tested")```
How's this? I maybe wrong
tough wagon
#

@slate swan

slate swan
#

are the \ needed

#

guesing not

tough wagon
#

yes

slate swan
#

the slashes go in the code??

tough wagon
#

but if you want to make all these replaces in one line, then they are not needed

tough wagon
slate swan
#

k

dusk pumice
#

slash connects the lines
So you need slash

dusk pumice
tough wagon
#

ehm

#

nvm...

dusk pumice
#

What is ehm and nvm

tough wagon
#

nvm = nevermind
ehm = like... sigh

dusk pumice
#

So I guess this was worng?

still tiger
#
@bot.command(name="transum")
async def _transum(ctx, link):
    message = await ctx.send(':loading:Solving...')
    request_response = requests.head(link)
    status_code = request_response.status_code
    if urlparse(link).hostname == "www.transum.org":
        if status_code != 404:
            transum_solve(link)
            filename = link.encode("utf-8").hex() + ".png"
            await message.edit(file=discord.File(filename))
            os.remove(filename) if os.path.isfile(filename) else None
        else:
            await message.edit(content=':error_404:')
    else:
        await message.edit(content='Specify a transum URL.')

Hi, this is my code for a bot I am making. However, when I run it, and run the command, it throws this error, anyway I can fix it?

File "/home/aarav/Desktop/main.py", line 62, in _transum
    await message.edit(file=discord.File(filename))
TypeError: Object of type File is not JSON serializabl
slate swan
#

didnt work

#

it just sends nothing now

tough wagon
#

error?

dusk pumice
#

What's the error code?
I must print something...

slate swan
#

literally no error

dusk pumice
#

No error?

slate swan
#

thats all it says at nthe bottom

tough wagon
#

oh i know what is the problem

tough wagon
#

i won't explain that dumb...

dusk pumice
#

||HaRd tO FiX ErRoR||

still tiger
tough wagon
#

||NoPe||

slate swan
#

its not sending

still tiger
#

I read the documentation and these are all the parameters

#

how do I edit a message with a file?

tough wagon
#

more code?

#

how do you get it

slate swan
#

its not empty

#

from database, i also set the message 3 different times before it

dusk pumice
still tiger
#

Well I thought about that but was just confriming if we can edit a message with a file

dusk pumice
still tiger
#

That is true

dusk pumice
#

So I guess bot cann't

still tiger
dusk pumice
#

HaHAHAH

dusk pumice
#

If file is png

tough wagon
#

aPi Of DiScOrD iS nOt SuPpOrTtInG eDiTiNg FiLeS

still tiger
#

Good idea, it is png

dusk pumice
#

I hope it workes...

dusk pumice
still tiger
#

Ok ill try and report back

dusk pumice
#

🙂

#
@bot.listen()
async def on_member_update(before, after):
  if before.guild.premium_subscriber_role not in before.roles and before.guild.premium_subscriber_role in after.roles:
    # The member just boosted
    await nitrohook.send(file=discord.File('nitro.jpg'))
    await nitrohook.send("boosted")
#

Will this cord work?

#

I Can't test it because I have no nitro

tough wagon
#

nitrohook

#

xD

dusk pumice
#

ah nitrohook is a Webhook.

tough wagon
#

but not defined

dusk pumice
#

I used dhook for the Webhook

tough wagon
#

niceeee

dusk pumice
#

Lol

tough wagon
#

wt..

dusk pumice
#

and

from dhooks import Webhook, Embed
tough wagon
#

i , i won't help)

dusk pumice
dusk pumice
tough wagon
#

o-o-o-0k

dusk pumice
tough wagon
#

it's just weird making webhooks without knowledge of how to define them

#

webhooks are only in channels, they cant be just like 'Private' you need to get or create it in channel

dusk pumice
#

i just didn't wanted to show my webhook url

#

so I changed it to private

calm vortex
#

!pypi dhooks

unkempt canyonBOT
tough wagon
#

omg

calm vortex
#

I see

dusk pumice
#

...?

#

Thannnnks?

#

||me AFK for 5min||

tough wagon
#

and what is reason to use dhooks?

#

discordpy includes webhooks

dusk pumice
#

Noreasons

calm vortex
dusk pumice
#

Huh????

#

dpy has webhook?

#

Didn't know that

#

and bye

tough wagon
calm vortex
#

@dusk pumice

from discord import Webhook, AsyncWebhookAdapter
import aiohttp

async with aiohttp.ClientSession() as session:
 webhook = Webhook.from_url('url-here', adapter=AsyncWebhookAdapter(session))
dusk pumice
#

👀

dusk pumice
#

?

#

\❌

still tiger
#

How would I attach a image to my embed from a relative file instead of url?

calm vortex
#

?

dusk pumice
#

hmm

still tiger
#

so instead of
url=http..
I would want
file=img.png

slate swan
dusk pumice
#

Um ok

slate swan
#

my name was felony

dusk pumice
#

Oh...it's sxcu

#

lol

#

I got to go now byebye

maiden fable
#

!local

unkempt canyonBOT
#

Thanks to discord.py, sending local files as embed images is simple. You have to create an instance of discord.File class:

# When you know the file exact path, you can pass it.
file = discord.File("/this/is/path/to/my/file.png", filename="file.png")

# When you have the file-like object, then you can pass this instead path.
with open("/this/is/path/to/my/file.png", "rb") as f:
    file = discord.File(f)

When using the file-like object, you have to open it in rb mode. Also, in this case, passing filename to it is not necessary.
Please note that filename can't contain underscores. This is a Discord limitation.

discord.Embed instances have a set_image method which can be used to set an attachment as an image:

embed = discord.Embed()
# Set other fields
embed.set_image(url="attachment://file.png")  # Filename here must be exactly same as attachment filename.

After this, you can send an embed with an attachment to Discord:

await channel.send(file=file, embed=embed)

This example uses discord.TextChannel for sending, but any instance of discord.abc.Messageable can be used for sending.

still tiger
#

@dusk pumice So it still ives that error when i try to edit an embed with an img

still tiger
odd walrus
#

inside a discord bot, i must use either one of BOT or CLIENT right its not possible to use both if not wrong?

still tiger
#

Whatever you intialize it as, it also could be imacoolbot or apiudkjqqden

#

for example bot = commands.Bot(command_prefix='-') could be thisisacoolbot = commands.Bot(command_prefix='-')

tough wagon
still tiger
odd walrus
#

cause im merging 2 scripts
one uses
client = discord.Client()
the other uses
client = commands.Bot(command_prefix=">")
causes it not to work

maiden fable
still tiger
#

Actually its fine, what I wanted to do isnt possible so I just delete the message and upload another one with a file instead of editing it

#

Also I have a question, people say to hide the token in an external file, why is this?

odd walrus
#

good question haha
i was thinking either they dont want to show it when showing their code or they want to make some config file for others to change the token easily

still tiger
#

Hmm

slender river
#

idk whyd yu use both in the first place tbh

#

id say yu just use commands.Bot since yu can work with everything that discord.Client provides and also add cmds as needed

#

would anyone know how to setup a counter with a bot by any chance? as in every time i run it on replit i want the amount of times the code has been ran to show up.

#

ive already made an array for the test count and setup another global var to be appended to the array when the codes ran but i dont know how to make the new value that was added stay

slate swan
#
@commands.Cog.listener()
    async def on_voice_state_update(self, member, before, after):
        time = datetime.datetime.utcnow().strftime('[%Y/%b/%d - %I:%M %p]')
        if after.channel:
            if not before.channel and after.channel:
                print(f"[+] {member} Joined {after.channel.name[2:]} at {time}")
        if before.channel:
            if before.channel and not after.channel:
                print(f"[-] {member} Left {before.channel.name[2:]} at {time}")

I have this, But when someone moves into another channel, It doesn't tell me, Can someone tell me what's the function for it?

#

Is there an api to change my bot token? Imagine I could change it if it gets logged somehow

slate swan
#

Shame

#

Would be cool the eh

#

Im not sure tho!

tough wagon
# slate swan ```py @commands.Cog.listener() async def on_voice_state_update(self, member,...
    @commands.Cog.listener()
    async def on_voice_state_update(self, member, before, after):
        time = datetime.datetime.utcnow().strftime('[%Y/%b/%d - %I:%M %p]')
        if before.channel != after.channel:
            if after.channel is None and before.channel is not None:
                print(f"[-] {member} Left {before.channel.name[2:]} at {time}")
            elif before.channel is None:
                print(f"[+] {member} Joined {after.channel.name[2:]} at {time}")
            else:
                print(f"[+] {member} Moved from {before.channel.name[2:]} to {after.channel.name[2:]} at {time}")```
slate swan
#

is there a way to get he user id on button click??

#

Im using nextcord

tough wagon
#

oh nextcord, then idk

slate swan
tough wagon
#

im using discordpy 2.0v

unkempt canyonBOT
#
Fat chance.

No documentation found for the requested symbol.

slate swan
slate swan
#

Urgh

#

Again?

slate swan
#

only thing i can think of is using SQL

#

to check wether a user left and re-joined another channel

#

or plain left

slate swan
#

Shush it works!

tough wagon
#

@slate swan no men, you are wrong)

slate swan
#

honestly idk how to use on_voice_state_update

#

Thanks guys!

#

you're right ngl

#

i just assumed

tough wagon
#

I'm not good at this english, what is ngl?

delicate moat
slate swan
#

not gonna lie

tough wagon
#

ok

delicate moat
#

How do I make a list of all user roles?

tough wagon
unkempt canyonBOT
#

property roles: List[Role]```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.

These roles are sorted by their position in the role hierarchy.
slate swan
#

member.roles

#

o welp

#

:.\

tough wagon
#

!pypi nextcord

unkempt canyonBOT
delicate moat
#

wait

delicate moat
#

wrong one one sec

tough wagon
#

ok

slate swan
#

it should return a list

delicate moat
#
Code:
@client.command()
@commands.has_permissions(manage_messages=True)
async def mute(ctx, member: discord.Member, *, reason=None):
  global bot_delete
  if not ctx.author.bot:
    role = discord.utils.find(lambda r: r.name == 'Muted', ctx.message.guild.roles)
    if role not in member.roles:
      print(member.roles)

Output:
[<Role id=896648465227055157 name='@everyone'>, <Role id=896653598220492811 name='MEE6'>]
tough wagon
#

it MUST return a list

delicate moat
tough wagon
#

no

slate swan
#

Ofc it doesn’t

#

It’s discord

delicate moat
#

then how do i make it return a list like that

tough wagon
#

but you can do it through [role.name for role in member.roles]

slate swan
#

let’s be real here.

delicate moat
slate swan
#

@tough wagon is on_voice_state_update useful at all?

#

i rarely see it

tough wagon
slate swan
#

putting logs aside

tough wagon
slate swan
#

|}p/0;-[-+*9

tough wagon
#

if you want voice logs: yes , if not: i think no

slate swan
#

sorry dust on my keyboard

tough wagon
#

lol

slate swan
#

so i usually avoid it

cinder horizon
#

how do i get this to be India?....or can i?

sullen shoal
#

str.title()
?
str is the variable

unkempt canyonBOT
#

str.title()```
Return a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase.

For example:

```py
>>> 'Hello world'.title()
'Hello World'
```  The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result:

```py
>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"
```...
cinder horizon
#

thenks

slate swan
tough wagon
#

lol

sullen shoal
slate swan
#

nice ty

tough wagon
#

there is also capitalize

unkempt canyonBOT
#

str.capitalize()```
Return a copy of the string with its first character capitalized and the rest lowercased.

Changed in version 3.8: The first character is now put into titlecase rather than uppercase. This means that characters like digraphs will only have their first letter capitalized, instead of the full character.
tough wagon
#
name = "geeks FOR geeks"
print(name.capitalize())```
unkempt canyonBOT
#

@tough wagon :white_check_mark: Your eval job has completed with return code 0.

Geeks for geeks
spring flax
#

can you log deleted stickers?

slate swan
#

is it possible to append letters to a string like i would do with a list..?

sullen shoal
#

.join()

cinder horizon
unkempt canyonBOT
#

str.join(iterable)```
Return a string which is the concatenation of the strings in *iterable*. A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") will be raised if there are any non-string values in *iterable*, including [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. The separator between elements is the string providing this method.
cinder horizon
sullen shoal
#

convert it to string first

tough wagon
lament mesa
cinder horizon
slate swan
spring flax
sullen shoal
#

these are some really basic stuff python can do, i hope you learn these things first before going for discord bots.

cinder horizon
tough wagon
#

@spring flax

slate swan
lament mesa
spring flax
tough wagon
spring flax
tough wagon
unkempt canyonBOT
slate swan
#

almost all questions are related to dpy 2.0 here

spring flax
#

oh thank you

sullen shoal
slate swan
#

I feel useless

spring flax
#

nvm it has png attr

tough wagon
tough wagon
trim briar
#

Hello

#

I have a doubt - I changed my prefix from ! to Flo but can't seem to have space in it. Eg. I have to use Floprefix instead of Flo prefix. How do I solve it?

tough wagon
#

you have a server prefix system?

#

or it's command_prefix='Flo'?

trim briar
#

Server Prefix Sys

tough wagon
#

hm

#

sed idk how to do that

trim briar
#

oh np

tough wagon
#

and there is case_insensitive for this

sullen shoal
#

oh

hasty iron
#

not the prefix

sullen shoal
#

i've done the server prefix sys once, it worked fine with spaces too, let me find the code one sec

tough wagon
errant shuttle
#

hey my bot is not joining the voice channel. here is my code

@client.command(pass_context = True)
async def join(ctx):
 
    channel = ctx.message.author.voice.voice_channel
    await client.join_voice_channel(channel)

here is the error

Ignoring exception in command join:
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 111, in join
    channel = ctx.message.author.voice.voice_channel
AttributeError: 'VoiceState' object has no attribute 'voice_channel'

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

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'VoiceState' object has no attribute 'voice_channel'

Someone please help me

hasty iron
#

do you even know what that does or are you just spitting random stuff you found

tough wagon
#

maybe, I think im not the worst person here?)

hasty iron
errant shuttle
hasty iron
tough wagon
errant shuttle
hasty iron
#

and client.join_voice_channel is not a thing

tough wagon
#

and channel.join()

hasty iron
#

stop copying old code

errant shuttle
sullen shoal
# sullen shoal i've done the server prefix sys once, it worked fine with spaces too, let me fin...

here it is, https://github.com/m-y-x-i/Kreklie-discord-bot/blob/main/cogs/server.py
(this project was coded before i knew about classes so i coded anything i could think of so the code is pretty spaghetti looking)

GitHub

This bot isn't for hosting. I'm just testing discord.py stuff with it. - Kreklie-discord-bot/server.py at main · m-y-x-i/Kreklie-discord-bot

errant shuttle
#

which tutorial shud i watch then?

hasty iron
#

none

thick sigil
#

docs

hasty iron
#

read the docs and experiment yourself

trim briar
#

I actually didn't understood your prefix way lol.

tough wagon
dusk pumice
#

Can i use 2 prefix in python?

---I'm back :D
tough wagon
trim briar
#

yes

dusk pumice
#

Huh?

#

WDYM

tough wagon
#

b = commands.Bot(command_prefix=['!', '?'])

#

and it will work with ! and with ?

dusk pumice
#

OH really?

tough wagon
#

yes

dusk pumice
#

I'm gonna try it

#

out

sullen shoal
trim briar
#

Btw, I have some commands that could also work in my bots DMs but since I changed the way of how my prefix works (I used json for my prefix in different servers so that means command_prefix = get_prefix). Now when I type the command in my bots DM, it gives the following error:

raise TypeError("command_prefix must be plain string, iterable of strings, or callable "
TypeError: command_prefix must be plain string, iterable of strings, or callable returning either of these, not NoneType

and also this it how it works:

@client.command()
async def help(ctx):
    await ctx.message.add_reaction("📭")
    def check(m):
        if m.author == ctx.author and not ctx.guild:
            return True
tough wagon
slate swan
#

How can I use proxy for my discord bot as sometime replit gets rate limited and my bot gets blocked temporarily

sullen shoal
#

check the type of get_prefix

#

or what it returns

tough wagon
sullen shoal
#

oh yeah

trim briar
slate swan
#

..

sullen shoal
trim briar
#

Indeed

thick sigil
tough wagon
thick sigil
#

return ["flo", "flO", "FLO"]

sullen shoal
# trim briar Indeed

replit uses shared ip, so it may get rate limited any time and secondly replit has a very easy to use database that will get you rid of json

tough wagon
#

just return a list

trim briar
trim briar
#

alright

sullen shoal
slate swan
#

so no way to bypass right?

sullen shoal
#

except creating thousands of discord accounts, no

slate swan
dusk pumice
trim briar
#

Thanks, it worked

#

but now

hasty iron
#

they last for like an hour, so i don’t see why you would want to bypass them

slate swan
hasty iron
#

then stop using replit

slate swan
hasty iron
#

reasons?

thick sigil
#

There are plenty of very cheaps vps

slate swan
#

I mean I am just a student and am not allowed to spend money on vps etc.....

hasty iron
#

then selfhost

sullen shoal
#

there are kids on discord giving people free hosting by buying one or two vps you may search for them. their service last for like a month or so then most of them get bankrupt

slate swan
#

not possible kek

hasty iron
#

then don’t host a bot

slate swan
trim briar
#

@sullen shoal what is the withspace that you are using

sullen shoal
trim briar
#

so could I use the same with my prefix?

errant shuttle
#

this is still not working

@client.command()
async def join(ctx):
    channel = ctx.author.voice.channel
    await channel.connect()
sullen shoal
unkempt canyonBOT
#

cogs/server.py line 20

if withspace:```
sullen shoal
trim briar
#

but could you give me an example of how exactly would I have to use it?

errant shuttle
#

here is the error

Ignoring exception in command join:
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 111, in join
    await channel.connect()
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/abc.py", line 1277, in connect
    voice = cls(client, self)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/voice_client.py", line 199, in __init__
    raise RuntimeError("PyNaCl library needed in order to use voice")
RuntimeError: PyNaCl library needed in order to use voice

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

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: RuntimeError: PyNaCl library needed in order to use voice
trim briar
errant shuttle
trim briar
#

PyNaCl

errant shuttle
#

opus?

hasty iron
#

read

trim briar
#

wait one sec

errant shuttle
#

oh

#

pynacl

hasty iron
#

pynacl isnt opus

#

!pypi PyNaCl

unkempt canyonBOT
#

Python binding to the Networking and Cryptography (NaCl) library

errant shuttle
#

btw any idea how i can use strip_after_prefix?

hasty iron
#

why do you want to use it

errant shuttle
hasty iron
#

what?

sullen shoal
#

okay let me try to give you an example then
lets say x is your db,

def prefix(prefix, space = None):
  if space is not None and space.lower() == 'withspace':
    x.set(prefix+' ')
  else:
    x.set(prefix)
heavy folio
#

how do i use ephemeral messages for my bot? i cant find the lib for that

sullen shoal
#

now if someone does,
.prefix kk
the prefix will be kk
and if .prefix kk withspace
it will be, kk

heavy folio
heavy folio
reef shell
hasty iron
#

why is it "withspace"

hasty iron
#

you dont have to bump them

sullen shoal
reef shell
unkempt canyonBOT
#

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

The callback associated with this UI item.

This can be overriden by subclasses.
heavy folio
#

could someone send the link for the lib for ephemeral messages

reef shell
#

do you not see what I'm redirecting you to?

trim briar
hasty iron
#

you need a db

trim briar
#

Which is better? - MySQL or SQLite

errant shuttle
hasty iron
#

postgresql

sullen shoal
errant shuttle
#

cuz its already included in python

trim briar
#

hmm

errant shuttle
trim briar
#

but don't really need a money sys

hasty iron
#

use a db eitherway

trim briar
#

I will try something with json though but if I get my head stuck around too long, then well It's time for a db

trim briar
slate swan
#
time = datetime.datetime.utcnow().strftime('[%Y/%b/%d - %I:%M %p]')

I have this but, It's 3 hours behind my timezone, How do I fix it please?

boreal ravine
heavy folio
#

how do i make a command require roles from different servers? im using if statements to check

#

or i can actually do @commands.has_any_role() but idk how to send an error message if the user doesnnt have any of the roles

heavy folio
#

i've never used it before

heavy folio
#

ty

slate swan
#
     fullamount = len(rconpayload)
     pamount = 0
     amount = 2000
     limit = 2000
     text = []
     while True:
       if fullamount >= limit:
        text.append(rconpayload[pamount:amount])
        fullamount -= limit
        pamount += limit
        amount += limit
        if fullamount <= limit:
          text.append(rconpayload[pamount:])
          break
     for part in text:
       await ctx.send(part)```

Okay ik this is techniclly for python, but I made this quick script meant to cut parts of string too long to be sent in a discord message by a bot. So i dont get the "invalid body field" error

Anyone knows how to make python not cut words in half since it reads charactors? not words?
slate swan
#

cuz it does this

sullen shoal
slate swan
#

wait so u mean..

sullen shoal
#

"i am myxi".split()[:1]

slate swan
#

oh fr

#

i never used split before

#

wait i lied

slate swan
slate swan
#

character*

#

near*

lone lichen
slate swan
#

k ty

lone lichen
#

Np

sullen shoal
slate swan
#

hmm

#

I think i see what u mena

#

@sullen shoal does python have an attribute for reading words withing a strng?

#

or am i gonna have to script that myself

#

by making it read spaces

#

?

sullen shoal
slate swan
sullen shoal
#

just split it by space then its a list of words

wheat moth
#

Hi, I have a question because I have error handling of command which saves errors to file and I want to get arguments used in command.
So how can I get arguments used in Spectate command from Spectate.error?
For example let's say someone wrote $Spectate br user and there is an error in the function how to save what this person wrote, like: ("br", "user")
My code is:

    @Spectate.error
    async def on_error(self, ctx: commands.Context, err: commands.CommandError):
        if isinstance(err, commands.CommandOnCooldown):
            await ctx.send(f"This command is on cooldown. Please try again after {round(err.retry_after, 1)} seconds.")
        else:
            self.Spectate.reset_cooldown(ctx)
            await ctx.send(
                f"Unknown error, please try using $desync and $sync again, if it still doesn't work try using this "
                f"command later or report this issue using `report` command")
            self.LeagueStats.error_log(ctx, traceback.format_exc()) # this function saves error as file.
lone lichen
tough wagon
#

it returns string &Spectrate br user

wheat moth
#

@tough wagon ty

slate swan
#

But i just realized this is going to require more then just a couple if statements

slate swan
#

I feel like im gonna need another for loop here

wheat moth
#

@lone lichen well ty for answer, but it gave me args of error in particular part of code not the command itself

lone lichen
wheat moth
#

np

slate swan
#

30.5% of 1.54MiB at 72.84KiB/s ETA 00:15
Is there something I can do?

#

@lone lichen alright thank you. I'm gonna have to do some big brain thinking for a second to formulate how im going to count the charectors in each item, then before it passes the charecter limit it cuts the string and save that part to a new list.

lone lichen
lone lichen
#

Yea that will be a bested for loop

#

Nested*

sullen shoal
# slate swan I feel like im gonna need another `for` loop here

the code will look spaghetti and i might prolly think of a better sol of it if i try later but heres what in my head,
get the len() of the string, then store it in var, x
then split it by space, iterate over it, do len() on every iteration then len(iteration) - x
when x hits 0, break the loop

slate swan
#

"the code will look spaghetti" indeed

tough wagon
lone lichen
slate swan
#

i wanted to do some big brain thinking

tough wagon
#

lol

slate swan
#

but i apperciate the code, im not gonna complain

#

lol

slate swan
#

string*

lone lichen
#

This will get u total number of characters in a list of strings basically

slate swan
#

right

#

Its like grabbing charectors in a slist

#

Now what I can do is

sullen shoal
lone lichen
slate swan
#

If the charectors exceed the charector limit, I can remove that LATEST item and copy the rest into a different list, and with a loop i can automate the this process

#

Sounds about right?

sullen shoal
lone lichen
#

Yea try that

slate swan
#

alr bet

unkempt canyonBOT
#
sum

sum(iterable, /, start=0)```
Sums *start* and the items of an *iterable* from left to right and returns the total. The *iterable*’s items are normally numbers, and the start value is not allowed to be a string.

For some use cases, there are good alternatives to [`sum()`](https://docs.python.org/3/library/functions.html#sum "sum"). The preferred, fast way to concatenate a sequence of strings is by calling `''.join(sequence)`. To add floating point values with extended precision, see [`math.fsum()`](https://docs.python.org/3/library/math.html#math.fsum "math.fsum"). To concatenate a series of iterables, consider using [`itertools.chain()`](https://docs.python.org/3/library/itertools.html#itertools.chain "itertools.chain").

Changed in version 3.8: The *start* parameter can be specified as a keyword argument.
slate swan
#

also what is summ?

tough wagon
#

me noobest noob in world

#

i forgot that it is sum

sullen shoal
#

i gotta try somehting hmm

slate swan
#

oh ok

lone lichen
tough wagon
sullen shoal
#

!e

iterable = ['eweef','wfwefw','wfwewf']
s = ''.join(iterable)
print(summ([len(item) from item in iterable]))
print(len(s)```
unkempt canyonBOT
#

@sullen shoal :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 3
002 |     print(summ([len(item) from item in iterable]))
003 |                           ^
004 | SyntaxError: invalid syntax
sullen shoal
#

oh

tough wagon
#

for

sullen shoal
#

!e

iterable = ['eweef','wfwefw','wfwewf']
s = ''.join(iterable)
print(summ([len(item) for item in iterable]))
print(len(s)```
unkempt canyonBOT
#

@sullen shoal :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 4
002 |     print(len(s)
003 |                 ^
004 | SyntaxError: unexpected EOF while parsing
tough wagon
#

summ working seriously?

slate swan
#

gg

sullen shoal
#

!e

iterable = ['eweef','wfwefw','wfwewf']
s = ''.join(iterable)
print(sum([len(item) for item in iterable]))
print(len(s))```
unkempt canyonBOT
#

@sullen shoal :white_check_mark: Your eval job has completed with return code 0.

001 | 17
002 | 17
sullen shoal
#

lol

#

as i said its same as that

tough wagon
#

sum!

sullen shoal
#

yeah i was wondering why master sent that code

#

if you just use len()

slate swan
#

Overcomplicating things episode 324

lone lichen
sullen shoal
#

the code they sent basically wont count the whitespaces

slate swan
tough wagon
#

uh, I forgot about join, dumb me

dapper cobalt
lone lichen
sullen shoal
#

all the whitespaces

#

in the string

lone lichen
#

Yes?

tough wagon
sullen shoal
#

that will just subtract 1 from len

#

one sec

lone lichen
#

Since he used split

hasty iron
#

huh?

lone lichen
#

And it splited where whitespaces are

hasty iron
#

cant you just strip the whitespaces

#

!d str.strip

unkempt canyonBOT
#

str.strip([chars])```
Return a copy of the string with the leading and trailing characters removed. The *chars* argument is a string specifying the set of characters to be removed. If omitted or `None`, the *chars* argument defaults to removing whitespace. The *chars* argument is not a prefix or suffix; rather, all combinations of its values are stripped:

```py
>>> '   spacious   '.strip()
'spacious'
>>> 'www.example.com'.strip('cmowz.')
'example'
```  The outermost leading and trailing *chars* argument values are stripped from the string. Characters are removed from the leading end until reaching a string character that is not contained in the set of characters in *chars*. A similar action takes place on the trailing end. For example:
sullen shoal
#

!e

iterable = ['eweef','wfwefw','wfwewf']
s = ' '.join(iterable)
print(sum([len(item) for item in iterable]))
#

oops

lone lichen
hasty iron
#

why?

#

that seems super useless

sullen shoal
#

now lets try that

lone lichen
#

Ayo

#

Why tf did we put string in a list to count all It’ s characters @slate swan

sullen shoal
#

!e

iterable = ['eweef','wfwefw','wfwewf']
s = ' '.join(iterable)
print(len(s))
print(sum([len(item) for item in iterable]))
print(len(s)-1)```
unkempt canyonBOT
#

@sullen shoal :white_check_mark: Your eval job has completed with return code 0.

001 | 19
002 | 17
003 | 18
lone lichen
#

Lmfao

hasty iron
#

wtf are you even doing

lone lichen
#

Bro just do len(original_string)

lone lichen
sullen shoal
lone lichen
hasty iron
#

if you want the amount of whitespaces removed, just len the original string then strip whitespaces and then len it again and substract to get the amount

sullen shoal
#

yeah ik

lone lichen
sullen shoal
sullen shoal
#

no

hasty iron
sullen shoal
#

it strips from starting and ending only

hasty iron
#

what?

lone lichen
hasty iron
#

!e ```
string = " h"
print(string.strip())

unkempt canyonBOT
#

@hasty iron :white_check_mark: Your eval job has completed with return code 0.

h
hasty iron
#

???

sullen shoal
#

im not talking about that

lone lichen
#

U two talking bout two different things

#

U both right

sullen shoal
#

im talking about all the white spaces in the string, not in index 0 and :-1

hasty iron
#

!e ```
string = "h e l l o "
print(string.strip())

unkempt canyonBOT
#

@hasty iron :white_check_mark: Your eval job has completed with return code 0.

h e l l o
slate swan