#discord-bots

1 messages ยท Page 611 of 1

slate swan
#

Or list comprehension

#

.text_channels, someone recently made guild.channels mistake earlier and wondered why it wouldnt send in random channel

slate swan
wicked atlas
#

Well, they never said specifcally a text channel

slate swan
slate swan
#

Nah just want to check it.

if discord.utils.get(guild.channels, name="lol"):
  print("This Channel exists!")
else:
  print("This Channel does not exist!")```

What if the channel name is `lol-xd`. Then it would be false right? So do I have to do something with `lol in name`
wicked atlas
slate swan
slate swan
wicked atlas
slate swan
#

if they do channel for channel ..... , That would be the channel object

#

im confused

#

so if i want the channel id, can i do

#

id for channel in guild.text_channels if channel.name == 'general_chat'

slate swan
#

oh ok

#

oh yeah i see now

#

oh i have actually used this b4

#

i needed to convert the keys of a dictionary where the keys were numbers but strings into a list of integers and used it

#
                        keylist = feetable.keys()
                        keylist = [int(i) for i in keylist]```
stone moon
#

how do I split the list for the id

wicked atlas
slate swan
#

i think we were just talking about what he needs

#

list comprehensions

stone moon
#

message.mentions is 1nin length

slate swan
#

mention.id for mention in message.mentions

wicked atlas
stone moon
slate swan
stone moon
#

thanks!

stone moon
#

comes up

slate swan
#

did u do :

#

actually u dont need :

#

dunno

#

what went wrong there tbh

stone moon
#

wdym :

stone moon
wicked atlas
slate swan
#

dont print it directly

#

do like a =

#

and then print a

stone moon
#

ohh

#

Iโ€™m so dumb lol

stone moon
slate swan
#
  if message.mentions:
     for member in message.mentions:
         await message.channel.send(f'{member.mention}')
wicked atlas
#

Dang, sorry, mentions, mixed up two problems there

wicked atlas
stone moon
#

thanks I appreciate it so much

slate swan
#

I have 2 reactions \๐Ÿ‘ and \๐Ÿ‘Ž Is there a way I could make a check to check for either one

#

Yes

#

how would I go about this

#

discord.utils.get(message.reactions,"๐Ÿ‘")

slate swan
#

You can make a check

#

To check reactions

#

yeah thats more the answer I was looking for

#

how would you do that though

#

im not sure how checks work

#

lambda reaction, user: reaction.emoji == '๐Ÿ‘'

#

that would work for one but how could I do 2

#

You can make the bot wait_for() a reaction and check if the reaction is the one you want

#

but how for 2

#

do it twice?

slate swan
#
await client.wait_for('reaction_add', check = lambda reaction, user: reaction.emoji == '๐Ÿ‘' or '๐Ÿ‘Ž')

would that work

#

oh , if you just want to check that there are 2 reactions , you can use reaction.count

#

no

slate swan
#

so if its ๐Ÿ‘ is does one thing
if its ๐Ÿ‘Ž it does another

#
lambda reaction, user: reaction.emoji in ['๐Ÿ‘' ,'๐Ÿ‘Ž']```
#

or , py lambda reaction, user: reaction.emoji == '๐Ÿ‘' or reaction.emoji=='๐Ÿ‘Ž'

#

then how could I differentiate which is which

#

and do something different depending on which is reactex

slate swan
#

so

if reaction.emoji == '๐Ÿ‘Ž':
  code
else:
  more code
#

sure

#

k thanks

slate swan
#

so

if reaction.emoji == '๐Ÿ‘Ž':
  return await ctx.send('you reacted with a thumbs down')

more code here
#

I have to check for another reaction as well

#

sure ig

#

How do i make a say cmd for my bot like >say Sus and the bot does that

final iron
slate swan
final iron
#
@client.command()
async def say(ctx, *, user_text):
    await ctx.send(user_text)
#

Indentation is probably wrong but you could fix that yourself

glass rock
#

Is there a way to make bots recognize reactions?

slate swan
#
if reaction.emoji == ':thumbsup:':
        await member.send(f'Congrats! Your suggestion: {suggestion} was accepted. And will be added soon')
        await channel2.send(embed=embed)
        await mes.delete()
    elif reaction.emoji == ':thumbsdown:':
        await member.send(f'Sorry! Your suggestion: {suggestion} was not accepted.')
        await mes.delete()

I have this code and im getting a error of inconsistant tabs and spaces error on the await channel2.send

final iron
#

You cannot use tabs and spaces in the same line

slate swan
#

im not

final iron
#

Reindent everything

slate swan
#

ok

#

it worked

slate swan
glass rock
slate swan
#
    @commands.command()
    async def get_channel(ctx, *, given_name=None):
      for channel in ctx.guild.channels:
        if channel.name == given_name:
          wanted_channel_id = channel.id

      await ctx.send(wanted_channel_id) # this is just to check ```
#

Trying to make a command to search for a channel and it gives the results/closest results

#

I'm not sure if this is the right way but this isn't working

slate swan
woeful crow
#
@client.event
async def on_guild_join(guild):
  owner = guild.owner
  await owner.send("Helllo!")

I'm getting AttributeError: 'NoneType' object has no attribute 'send'

full valley
#

How can I create a vc with only certain members seeing it?

slate swan
woeful crow
#

I have intents enabled

slate swan
#

in the code as well?

woeful crow
#

Yeah

slate swan
#

show your intents part

#

and commands.Bot

woeful crow
#
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix = ',',description="Hello there", intents=intents)
slate swan
#

@slate swan nice pfp

slate swan
slate swan
slate swan
pliant gulch
#

This isn't an intents issue

woeful crow
#

ah, good idea thanks

pliant gulch
unkempt canyonBOT
#

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

Retrieves a [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.

Note

This method is an API call. If you have [`discord.Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_user()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_user "discord.ext.commands.Bot.get_user") instead.
slate swan
#
Ignoring exception in command suggest:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.8/site-packages/nextcord/ext/commands/core.py", line 168, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/container/bot.py", line 57, in suggest
    reaction.emoji = None
UnboundLocalError: local variable 'reaction' referenced before assignment

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

Traceback (most recent call last):
  File "/home/container/.local/lib/python3.8/site-packages/nextcord/ext/commands/bot.py", line 995, in invoke
    await ctx.command.invoke(ctx)
  File "/home/container/.local/lib/python3.8/site-packages/nextcord/ext/commands/core.py", line 895, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/container/.local/lib/python3.8/site-packages/nextcord/ext/commands/core.py", line 177, in wrapped
    raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: UnboundLocalError: local variable 'reaction' referenced before assignment
pliant gulch
#

Because they show that their bot identifies with guild member intents on

#

So this is probably just a cache issue

slate swan
#

reaction.emoji = None

#

its not even in your code

#

maybe you didnt save the code and rerun it

#

its there

glass rock
#

how do i link channels using channel ids in DMs?

slate swan
#

<#CHANNELID>

glass rock
#

ye doesnt work

pliant gulch
#

It won't work in DMs

glass rock
#

exactly

slate swan
glass rock
#

is there a workaround?

pliant gulch
#

And I don't know of any workaround

glass rock
glass rock
maiden fable
#

Lemme show u

pliant gulch
#

It does work

glass rock
#

wot

maiden fable
pliant gulch
#

Are you sure you're in the same server as the channel?

maiden fable
#

Hehe @glass rock click on it

#

U will be redirected to our DM

glass rock
#

no lol

maiden fable
#

Oh hmm

#

Does for me tho

pliant gulch
#

Show's up as deleted channel on my client

maiden fable
pliant gulch
#

Either way, yea I just tested you can mention channels in DMs

glass rock
maiden fable
#

The difference is of the PoV

slate swan
#

I got it for him

slate swan
pliant gulch
#

Yea... I know you can mention channels in DMs

#

I just said so didn't I?

pliant gulch
slate swan
#

swear it said can't

glass rock
#

darn typos

#

i accidentally added a $ before {

#

thats why error ๐Ÿ˜ฆ

sullen shoal
unkempt canyonBOT
sullen shoal
#

uh wrong reply

slate swan
#

@sullen shoal

#

set object

#

i s not callable

sullen shoal
#

yes, its not

slate swan
#

lol

#

You dont laugh in russia

sullen shoal
#

dont call it

slate swan
jaunty terrace
#

if "Hello" in message.content:??

sullen shoal
#

also where is line 19?

slate swan
sullen shoal
#

@bot.command

slate swan
#

Low-key sherlocks discord bot will eventually be the ai that destroys earth

slate swan
slate swan
#

Comrade aint dead

#

ew replit

slate swan
#
import discord
import os
import time
import discord.ext
from discord.utils import get
from discord.ext import commands, tasks
from discord.ext.commands import has_permissions,  CheckFailure, check
from keep_alive import keep_alive

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

@bot.event
async def on_ready():
    await bot.change_presence(status= discord.Status.idle, activity=discord.Game('Nuke Nuke'))
    print("Comrade Ain't Dead") 
    

@bot.command
async def on_message(message):
  if message.author == bot.user:
    return

  elif message.content('Hello'):
    await message.channel.send('Hello Comrade') 

  elif message.content('Hi'):
    await message.channel.send('Hi. Did ya nuke USA?')

  elif message.content('comrade', 'Comrade'):
    await message.channel.send('Fuck You') 

  elif message.content('LMAO'):
    await message.channel.send('You Dont Laugh In Russia')  

  elif message.content('Anime'):  
    await message.channel.send('Anime Sucks You Crazy MF')

  if 'i solemnly swear that i am upto no good' in message.content.lower():
    role = discord.utils.get(message.guild.roles, id=904021392998146118)
    await message.author.add_roles(role)
  elif 'mischief managed' in message.content.lower():
    role = discord.utils.get(message.guild.roles, id=904021392998146118)
    await message.author.remove_roles(role)
  await bot.process_commands(message)

keep_alive()
bot.run("TOKEN")
slate swan
#

it doesnt reply on Hi or Hello or anything

#

@slate swan

slate swan
slate swan
#

take my IP idc

#

Thats a local ip anyway

slate swan
#

step 1 get off replit

#

if 'hello' in message.content.lower():
await message.author.channel.send(message)

#

let me know when your done with that

#

?

slate swan
#

yea no

#

use heroku

#

it is on stop for now

slate swan
#

idk why

#

replit isnt worth it

slate swan
#

how do slash commands work

slate swan
#

i dont have slash commands

slate swan
sullen shoal
slate swan
#

something wrong

#

cuz when i do >say Test

#

it doesnt work

#

@sullen shoal

final iron
#

You're missing an @

slate swan
#

lol

slate swan
#

i added it

#

still doesnt work

final iron
#

Did you save and rerun your code?

tawny knoll
#

if you have an errorhandler cog, how would you invoke custom error messages for commands?

#

everytime an error hits it runs both messages

slate swan
#

I reckon its likely due to on_message not hitting process comands line

slate swan
#

my bot prefix is >

final iron
#

Can we see your entire 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.

slate swan
#

Put ur on_message into @bot.event

#
import discord
import os
import time
import discord.ext
from discord.utils import get
from discord.ext import commands, tasks
from discord.ext.commands import has_permissions,  CheckFailure, check
from keep_alive import keep_alive

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

@bot.event
async def on_ready():
    await bot.change_presence(status= discord.Status.idle, activity=discord.Game('Nuke Nuke'))
    print("Comrade Ain't Dead") 
    
@bot.event
async def on_message(message):
  if message.author == bot.user:
    return

  elif message.content.startswith('Hello'):
    await message.channel.send('Hello Comrade') 

  elif message.content.startswith('Hi'):
    await message.channel.send('Hi. Did ya nuke USA?')

  elif message.content.startswith('Comrade'):
    await message.channel.send('Shut Up Fool') 

  elif message.content.startswith('hello'):
    await message.channel.send('Hello Comrade')  

  elif message.content.startswith('hi'):
    await message.channel.send('Hi. Did ya nuke USA?')   

  elif message.content.startswith('comrade'):
    await message.channel.send('Fuck You') 
    
  elif message.content.startswith('LMAO'):
    await message.channel.send('You Dont Laugh In Russia')  


  if 'i solemnly swear that i am upto no good' in message.content.lower():
    role = discord.utils.get(message.guild.roles, id=904021392998146118)
    await message.author.add_roles(role)
  elif 'mischief managed' in message.content.lower():
    role = discord.utils.get(message.guild.roles, id=904021392998146118)
    await message.author.remove_roles(role)
  await bot.process_commands(message)

@bot.command
async def say(ctx, *, user_text):
  await ctx.send(user_text) 

keep_alive()
bot.run("TOKEN")
#

Should work tbh

slate swan
cerulean osprey
#

Add () at the end of @bot.command?

final iron
#

bot.command()?

slate swan
final iron
#

You're missing the brackets

cerulean osprey
#

^

slate swan
#

wait

#

works

slate swan
#

await ctx.message.delete()

#

To delete the command

#
@bot.command()
async def say(ctx, *, user_text):
  await ctx.send(user_text)
slate swan
#

B4 ctx.send

#

Do u wanna delete the command

#

Or the output?

#
@bot.command()
async def say(ctx, *, user_text):
  await ctx.mssage.delete()
  await ctx.send(user_text)
#

Yh

#

Message

#

Not mssage

slate swan
#

Yh

#

?

quick gust
#

ctx.user_text.delete

#

since thats the param

slate swan
#

Yeah

#

Like that

slate swan
tropic briar
#

Does the bot message twice if we have 2 listeners in the code

cinder horizon
#

how do we get the server avatar?

sullen shoal
tropic briar
sullen shoal
#

unless, you have named the function same, it should work

tropic briar
#

Ohh

#

๐Ÿ‘

slate swan
#

using premium_since how can i find out how long a members been boosting for

#

would i have to do something like member.premium_since(UTCnow - 30%d)

#

or whatever the syntax is

slate swan
#

Purge Command help @slate swan@quick gust

#

await ctx.channel.purge(amount=amount)

#

Enjoy

sullen shoal
unkempt canyonBOT
#

datetime.strftime(format)```
Return a string representing the date and time, controlled by an explicit format string. For a complete list of formatting directives, see [strftime() and strptime() Behavior](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior).
sullen shoal
slate swan
pale zenith
#

???

#

wdym just this

slate swan
pale zenith
#

no?

#
  1. wtf is user text supposed to be/do
  2. where are you defining amount
slate swan
pale zenith
#
  1. โฌ†๏ธ
#

they just told you how to purge a specific amount of messages in a channel

#

now YOU make the command using the information.

#

and no what you did looks about wrong comfyblob

jaunty terrace
#

@thorny sequoia

slate swan
#

?

pale zenith
#

amount: int = 5 so discord.py converts it / attempts to convert it to an integer.

#

if not then it will raise an error saying amount must be int, got str inetead.

#

but for the rest, seems about rigt

slate swan
pale zenith
#

yes where you define the function

#

those are what d.py calls converters

slate swan
slate swan
#
@bot.command()
async def purge(ctx, amount: int = 5):
    await ctx.channel.purge(amount=amount)
#

@pale zenithcorrect?

slate swan
#

dont mind me

#

I am annoying

slate swan
#

didnt work

pale zenith
#

where is the decorator?

slate swan
pale zenith
#

:tias:

slate swan
pale zenith
#

i dont have the emoji anymore rooSob

#

i had a try-it-and-see emoji

slate swan
#

lol

#

@pale zenith

pale zenith
#

T I A S

#

Try It And See

slate swan
#

aaaaaa

#

worked now

twin moon
#

I cant import ipc from nextcord.ext

maiden fable
#

@grand lagoon this isn't the correct channel for all this...

sullen shoal
#

?

maiden fable
#

Please stop else I will have to ping the mods

grand lagoon
#

ok

maiden fable
#

Please delete those GIFs

quick gust
slate swan
quick gust
slate swan
quick gust
#

change to limit=amount

slate swan
quick gust
#

worked?

slate swan
#

it worked

quick gust
#

cool

slate swan
#

ye

#

i am learning a bit

tall dust
#

!warn 880878204863254600 don't drop out of context gifs in an on-topic channel

unkempt canyonBOT
#

:x: The user doesn't appear to be on the server.

tall dust
#

alright then

slate swan
tall dust
slate swan
slate swan
#

can someone help me with his lemon_thinking

slate swan
#

i want to make a snipe command that doesnt snipe blacklisted words

slate swan
#

wanna check my code ?

brisk helm
#

yes

slate swan
#

a json file is more than enough

#
class snipe(commands.Cog):
    def __init__(self, bot,message=None,author=None,blacklisted_stuff=None):
        self.bot = bot
        self.message = message
        self.blacklisted_stuff = [] if blacklisted_stuff is None else blacklisted_stuff
        self.author = author
    async def cog_command_error(self, ctx, error):
        await ctx.send(embed=discord.Embed(title='hey, dont error me ๐Ÿ˜”',description=error))
    @commands.Cog.listener()
    async def on_message_delete(self,message):
        if message.author.id == 218438244289740800:
            self.message = '**cants snipe boot**'
            self.author = message.author
        if message.author.bot:
            return
        if not any([term in message.content.split() for term in self.blacklisted_stuff]):
            self.message = message.content
            self.author = message.author
    @commands.command()
    async def snipe(self,ctx):
        if self.message is None: return await ctx.send('there are no deleted messages')
        embed = discord.Embed()
        embed = discord.Embed(title="   ",description=f"{self.message}")
        embed.set_author(name=self.author.name,icon_url=self.author.avatar_url)
        embed.set_thumbnail(url=self.author.avatar_url)
        embed.set_footer(text=f'requested by {ctx.author.name}',icon_url=self.author.avatar_url)
        await ctx.send(embed=embed)
    @commands.command()
    @commands.has_permissions(administrator=True)
    async def blacklist(self,ctx,stuff=None):
        if stuff is None: return await ctx.send('pass some shit to blacklist dude')
        with open('blw.json') as fhand:
            x = json.load(fhand)
        with open('blw.json','w') as fhand:
            x.append(stuff)
            z = x 
            json.dump(z,fhand)
            self.blacklisted_stuff = z
            await ctx.send('added that word in the blacklist file')```
brisk helm
#

Dont use json as db

slate swan
#

i'm not

#

maybe lemon_thinking

#

but either ways check that

brisk helm
#
    @commands.Cog.listener()
    async def on_message_delete(self,message):
        if message.author.id == 218438244289740800:
            self.message = '**cants snipe boot**'
            self.author = message.author
        if message.author.bot:
            return
        if not any([term in message.content.split() for term in self.blacklisted_stuff]):
            self.message = message.content
            self.author = message.author``` Why you use on_message_delete not on_message
slate swan
#

How do I get user id from a mention?

#
command = kwargs.get("args")
        if await author_is_mod(message.author, self.storage):
            if len(command) >= 1:
                if command[0]:
                    guild_id = str(message.guild.id)
                    user_id = command[0]
                    muted_role_id = int(self.storage.settings["guilds"][0][guild_id]["muted_role_id"])
                    print(user_id)
                    try:
                        print(user_id)
                        user = await message.guild.fetch_member(user_id)
#

This is what i have rn

slate swan
#

not working

brisk helm
#

you need to get user

slate swan
#

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

#

Is there any way to track these invites? And like delete them or track how many users have joined?

slate swan
brisk helm
slate swan
#

but the guy is mentioning the user

slate swan
slate swan
#

I can use a json file to store data

brisk helm
slate swan
# slate swan wdym

you save the invite codes and the uses in the database, when someone joins the server you check the server's invites with the ones you have in your db, and when one of them has more uses than what you have in your database, that's the invite the person joined used

slate swan
#

json is not a database

quick gust
slate swan
#

it can be used to store data tho ๐Ÿ™‚

#

thats how I store stuff lmao, cbf learning a db

slate swan
slate swan
slate swan
#

you got the docs for that?

slate swan
#

you just need an invite object and then .delete on it

slate swan
#

!d discord.Invite.delete

unkempt canyonBOT
#

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

Revokes the instant invite.

You must have the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to do this.
quick gust
slate swan
#

alr ty bossman

jade tartan
#

How do you make a command tag for example when a user joins they do a !verify and then they follow the instructions? Because i want my bot to be like this

#

Does that make sense?

slate swan
#

Ok i have another problem I have an unban command but I cant unban the user AttributeError: 'str' object has no attribute 'id'

#
    guild = bot.guilds[0]
    channel = bot.get_channel(91079377950838401)
    await channel.send(guild.invites())
slate swan
torpid dew
#

hi, i am trying to make a random discord tag generator, code so far doesn't work, nothing happens when i do command

@client.command()
async def tag(ctx):
  randomtag = random.randint(1,9999)
  if len(randomtag) == '1':
    await ctx.send(f'#000{randomtag}')
  if len(randomtag) == '2':
    await ctx.send(f'#00{randomtag}')
  if len(randomtag) == '3':
    await ctx.send(f'#0{randomtag}')
  else:
    await ctx.send(f'#{randomtag}')
#

int doesnt work with len, how else do i do it

unkempt canyonBOT
#

Hey @slate swan!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

โ€ข If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

โ€ข If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

slate swan
#

sure

brisk helm
#

??

slate swan
#

i fixed it lemon_sweat

brisk helm
#

uhhh nice

slate swan
#

Ayo i want to make a roast cmd for my bot

#

like dank memer

slate swan
#

starting from 1 does not make sense

slate swan
#

Oh so you want it to include tags starting with 0 too , use >=< instead of len

torpid dew
slate swan
slate swan
slate swan
#

Nah

slate swan
#

i will use random choice

#

Assuming you're aware what api is , it will return roasts without hardcoding anything , whereas the string method would require you to add strings by yourself

slate swan
#

output: ```
[<Invite code='AB5XmpEj' guild=<Guild id=910126069003190292 name='BotTesting' shard_id=None chunked=False member_count=8> online=None members=None>,

<Invite code='CvR8K2U7' guild=<Guild id=910126069003190292 name='BotTesting' shard_id=None chunked=False member_count=8> online=None members=None>,

<Invite code='xp7pUTRq' guild=<Guild id=910126069003190292 name='BotTesting' shard_id=None chunked=False member_count=8> online=None members=None>]


code: ```py
    guild = bot.guilds[0]
    channel = bot.get_channel(910793779508838401)
    print(await guild.invites())

How am I able to create a for loop that can sort through EACH invite, and look for things inside of the guild, such as member_count?

#

The most basic for-loop...

for invite in invites_list:
    print(invite.guild.member_count)
#

And of course, replace invites_list with your actual list of invites

#

ty

#

didn't know how to iterate through the guild

#

You don't

#

through the list

#

Basic for loop

#

One of the first things you learn when learning Python

#

If you ever did it

#

damn no need to roast me ๐Ÿ’€

#

Just saying, an advanced knowledge of Python is kind of required for making bots

opaque sun
#

Help anyone know why i can't improt discord?

slate swan
#
import discord
opaque sun
#

Doesnt work

#

Even after i installed it

slate swan
#

Have you installed it?

opaque sun
#

Yes

slate swan
#

In the correct version?

opaque sun
#

Pip show discord
Name: discord
Version: 1.7.3
Summary: A mirror package for discord.py. Please install that instead.
Home-page: https://github.com/Rapptz/discord.py
Author: Rapptz
Author-email:
License: UNKNOWN
Location: c:\users\yunish\appdata\local\programs\python\python39\lib\site-packages
Requires: discord.py
Required-by:

GitHub

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

scenic lark
#

How can I have data stored in json file show in per field in one embed?

jade tartan
#

Does any one know how to make this?

opaque sun
#

pip3 install discord
Requirement already satisfied: discord in c:\users\yunish\appdata\local\programs\python\python39\lib\site-packages (1.7.3)
Requirement already satisfied: discord.py>=1.7.3 in c:\users\yunish\appdata\local\programs\python\python39\lib\site-packages (from discord) (1.7.3)

#

Umm so what do i do

#

Is my python broken

slate swan
opaque sun
#

I can't import it

slate swan
#

You can always

#

Just write it

#

Then you eventually get an error when running

opaque sun
#

Ok

#

I havent made a bot i was gonna start

#

But it failed miserably

slate swan
#

Just go in the cmd

opaque sun
#

Ok

#

Then what

slate swan
#

And type python3 I guess

opaque sun
#

And i download it?

slate swan
#

Download?

opaque sun
#

Leads me to a microsoft store page

#

On python 3.9

slate swan
#

And what if you type python

opaque sun
#

3.9.7

slate swan
#

But no Microsoft store?

opaque sun
#

I think thats cause i installed it just now

#

Nop

slate swan
#

Then type import discord after you've typed python

opaque sun
#

Nope still error

hot shadow
#

What error?

slate swan
#

What kind of error

opaque sun
#

Traceback (most recent call last):
File "C:\Users\Yunish\PycharmProjects\discord\main.py", line 1, in <module>
import discord
ModuleNotFoundError: No module named 'discord'

slate swan
#

As I said

#

Don't make a project

opaque sun
#

Ok i closed it

hot shadow
#

Import the module from the REPL

slate swan
#

You created a virtual environment which doesn't contain discord.py in it.

opaque sun
slate swan
#

When you create a project on PyCharm don't create a new virtual environment

#

If you notice , the folder you use for your bot is named discord

jade tartan
#

Well ig no body wants to answer me maybe ill just talk to someone in private

opaque sun
#

Ok

#

So il just delete the project ig

slate swan
jade tartan
opaque sun
slate swan
#

No

slate swan
#

Since it's the folder where your project is, not a folder in that project folder

#

That's not related to your error , but would be problematic later

opaque sun
slate swan
jade tartan
slate swan
#

also , it needs member intents enabled

jade tartan
opaque sun
#

Still doesnt work

#

I think the only option here is to get a new PC

slate swan
#

wut

opaque sun
#

Idk

slate swan
#

code:

    for invites in await guild.invites():
        print(invites)
        print(invites.guild.member_count)

Output:

dsc.gg/abc
8
dsc.gg/bb4
8
dsc.gg/123
8```
The discord . gg part works, but the invites are stuck on 8. Anyone know why this is?
#

they should output 8, 0, 16

#

Why should the output be different

#

The guild member count doesn't change

#

There are 8 members in your guild

#

And not 8, then 0 and then 16 members

opaque sun
#

Oh yea winrar so what you said to do did not work any other sugestions?

scenic lark
#

Can someone help me too? I want to make a field per data stored in json but its just sending multiple embeds instead of adding fields

slate swan
#

invites.uses

#

!d discord.Invite.uses

unkempt canyonBOT
slate swan
#

ty lemme read

shrewd minnow
#

Hi! Can anyone help me find a good reference for comparing emojis here in Discord? I'm trying to do something whenever a specific emoji is used as reaction.

valid perch
valid perch
slate swan
#

is there any way to check when a new invite has been created. Like on_member_join, but like on_create_invite. If not, I can always loop through to find new invites.

unkempt canyonBOT
#

discord.on_invite_create(invite)```
Called when an [`Invite`](https://discordpy.readthedocs.io/en/master/api.html#discord.Invite "discord.Invite") is created. You must have the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to receive this.

New in version 1.3.

Note

There is a rare possibility that the [`Invite.guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Invite.guild "discord.Invite.guild") and [`Invite.channel`](https://discordpy.readthedocs.io/en/master/api.html#discord.Invite.channel "discord.Invite.channel") attributes will be of [`Object`](https://discordpy.readthedocs.io/en/master/api.html#discord.Object "discord.Object") rather than the respective models.

This requires [`Intents.invites`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.invites "discord.Intents.invites") to be enabled.
slate swan
#

ty

brittle ingot
#

I would suggest to anyone, if you have free time just explore the docs a bit more. Not only will you learn new things but even find inspiration for additions to your bot.

slate swan
#

^^

brittle ingot
#

Discord will be releasing a new text input component soon, im pretty sure it has to do with the image I sent yesterday. Essentially a component that will allow developers to create in platform forms

fast tree
#

Hey guys

#

So,

#

description=f"{moderator.mention}" This is my code

#

moderator=discord.utils.get(ctx.guild.roles, id=911791547786342461)

#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'moderator' is not defined

#

Can someone help?

brittle ingot
#

Is it below or above your description?

fast tree
#

above

brittle ingot
#

Can you show a SS of your code or paste it in code block format?

#

!paste

#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

brittle ingot
#

There we go

fast tree
#

Sure

shrewd minnow
fast tree
#

Give me a minute

slate swan
#
import discord
from discord.ext import commands, tasks


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

@bot.event
async def on_ready():
    print('bot in active')
    await bot.change_presence(activity=discord.Streaming(name='xxx', url='xxx'))

@bot.event
async def on_member_join(member):
    await member.send('Private message')

any reason why this isn't working?

quick gust
#

error?

slate swan
#

none

#

just wont run

#

like on member join

brittle ingot
slate swan
#

nothing happens

slate swan
#

k lemme change

#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

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

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.

slate swan
#

give that a good read

quick gust
#

you're defining moderator inside the embed?

valid perch
fast tree
brittle ingot
#

Oh good catch that completely evaded me ๐Ÿคฃ

fast tree
#

Lol

#

I got an error

#

raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'tuple' object has no attribute 'mention'

novel bolt
#

hii,
how do we wait for message like on message inside a cog?

quick gust
#

@commands.Cog.listener

brittle ingot
#

Same but uses the decorator ^^

fast tree
#

Moros, could you help?

novel bolt
fast tree
#

?

quick gust
#

Could u send the updated code so I can check for myself?

fast tree
#

Ofc

#
@bot.command()
async def hanamiteam(ctx):
    moderator = discord.utils.get(ctx.guild.roles, id=911791547786342461)
    embed = discord.Embed\
            (

        title="***โ—ˆ ๐‡๐€๐๐€๐Œ๐ˆ ๐“๐„๐€๐Œ โ—ˆ***",
        description=f"{moderator.mention}\n\nโžฅ x \n\n<@&{911791651926728744}>\n\nโžฅ x\n\n<@&{911791801143296031}> \n\nโžฅ x\n\n<@&{911791957158821888}>\n\nโžฅ x \n\n<@&{911792064956596225}>\n\nโžฅ x\n\n<@&{911792168161640559}> \n\nโžฅ x\n\n<@&{911792284465504277}>\n\nโžฅ x \n\n<@&{911792501264887838}>\n\nโžฅ x\n\n <@&{911792601546502255}>\n\nโžฅ x\n\n<@&{911792601546502255}>\n\nโžฅ x\n\n<@&{911792737643274273}>\n\nโžฅ x ",
        colour=discord.Colour.purple(),
        timestamp=datetime.datetime.utcnow()
quick gust
#

alright

steel oasis
#

Hey I need help with a command in my bot. It's supposed to get the top 50 results of a leaderboard here's my current code idk how to make it send the top 50 results. ```py
@bot.command()
async def lb(ctx, *, lbname):
lb = requests.get("https://api.hyperlandsmc.net/leaderboards")
lb = lb.json()
name = lb[f'{lbname}']
await ctx.send(f'yoo this works')

quick gust
#

could you remove id=911791547786342461

fast tree
#

Alr

quick gust
#

and interchange it with,
name="RoleNameHereCaseSensitive"

fast tree
#

Alr

quick gust
#

Should look something like this

moderator = discord.utils.get(ctx.guild.roles, name="RoleNameHereCaseSensitive")```
fast tree
#

moderator = discord.utils.get(ctx.guild.roles, name="911791547786342461")

quick gust
#

no the name

fast tree
#

ye

quick gust
#

not the role id

fast tree
#

Oh ye ye I pasted the wrong

quick gust
#

okay change it with name and lmk if it works

fast tree
#

Omg, it did

quick gust
#

cool!

fast tree
#

How can I do it with more Roles?

#

just change moderator?

quick gust
#

uh

#

i dont really know

#

haven't tried

fast tree
#

I'll try, thank you really much

quick gust
#

and making a new variable for each role would be inefficient

novel bolt
quick gust
#

could you show the entire event? in codeblocks

#

!codeblock

unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

novel bolt
#

i mean i wanted it to listen to messages only after a command is called

quick gust
#

oh

maiden fable
novel bolt
quick gust
#

oh, no the listener wont work there i think

novel bolt
#

oh

#

so wat can we use?

quick gust
#

thats basically a bot.event but in a cog

novel bolt
#

yeah ๐Ÿ˜“

quick gust
#

But I still dont understand what you want the command to do

novel bolt
novel bolt
quick gust
#

yeah then you can do what Skelmis said

novel bolt
#

oh ok i will try it

honest shoal
#

can we make watch together links from old library?

maiden fable
#

Oh wait, yes

#

My bad ^^^

#

!d discord.VoiceChannel.create_invite

unkempt canyonBOT
#

await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates an instant invite from a text or voice channel.

You must have the [`create_instant_invite`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.create_instant_invite "discord.Permissions.create_instant_invite") permission to do this.
honest shoal
#

thanks for it

novel bolt
broken dirge
#

Why do I get an error that the message is empty?

#

x01 is int

novel bolt
oak falcon
#

hi guys, what are webhooks? are those like webview in Android?

sullen shoal
broken dirge
sullen shoal
slate nymph
#

or desktop site discord web

sullen shoal
#

i disagree with that

#

webhooks can be sent using the discord api, it doesnt need bot user tokens to be sent

#

it can only be sent in a specific channel

slate nymph
sullen shoal
#

You can MAKE them

#

you dont NEED them to be sent

shadow wraith
#

does anyone know how to pin a message using the bot?

sullen shoal
#

anyone having the webhook URL can use it, it has rate limits and you can normal messages, embeds, images, that look like a message sent by a bot, the difference is that, it doesnt have a profile because its not a bot

shadow wraith
#

i tried doing pin_message but it doesn't work

slate swan
unkempt canyonBOT
#

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

Pins the message.

You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to do this in a non-private channel context.
broken dirge
#

Do you guys know how to delete message after let's say 5 seconds

shadow wraith
#

oh ๐Ÿ’€

broken dirge
slate swan
#

await asyncio.sleep(5)

shadow wraith
slate swan
#

No, only asyncio

sullen shoal
#

time.sleep will block the code

shadow wraith
#

oh lmao

shadow wraith
valid niche
#

Or do message.delete(delay=(seconds))

sullen shoal
#

i dont think it has that keyword, delay

slate swan
unkempt canyonBOT
#

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

Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") from the destination.
sullen shoal
#

!d discord.Message.delete

shadow wraith
#

๐Ÿ’€

sullen shoal
#

oh it does

valid niche
valid niche
slate swan
quick gust
slate swan
#

No

#

Doesn't have the same utility

#

Wanted to use purge after x seconds

#

At least that's what I understand

quick gust
#

Ah

#

I see

#

I thought they wanted to delete a message sent by the bot

slate swan
#

Not what I understood

#

But if it's the case, delete_after is right

quick gust
#

Nah, I see what you mean now

scenic lark
#

I have this code saving in my json file but whenever it saves it puts curly brackets with no information in it and under it is where it saves all the data, is there a way to remove that here is the code

with open('quotes.json','r') as f:
        quotes=json.load(f)
    try:
        for current_user in quotes["users"]:
                current_user['time'] == time
                current_user['quote'].append(message)
                if username != current_user['name']:
                    current_user['name'] = username
                    break
    except:
        quotes["users"].append({
         'name':username,
         'time': time,
         'quote': message,        
        })```
slate swan
#

I mean, I can also be wrong shrug

valid niche
#

With purge, if you mean put a delay between each message, you will need to do a for loop of history and an asyncio.sleep inside

broken dirge
valid niche
#

If you just wait to wait before executing the purge, put the asyncio.sleep before the purge

#

@broken dirge read my solutions above

#

Depending on what you want

sullen shoal
#

i dont see any advantage of doing that

scenic lark
broken dirge
slate swan
#

What do you exactly want to do

broken dirge
slate swan
#

Do you use wait_for to get the input of the user?

slate swan
#

And the message you want to delete is which one?

broken dirge
#

Mine

slate swan
#

So just one

broken dirge
#

My response

#

Yes

slate swan
#

Well

#

When you use wait_for and wait for a message you get a message object in return

#

Then you can simply use await asyncio.sleep(x) and then await message.delete()

broken dirge
#

Ofc if that's possible

#

I don't think it is with asyncio function

slate swan
#

I mean

#
# command stuff
msg = wait_for....
# do stuff with the user response
await asyncio.sleep(x)
await msg.delete()
#

You will get the response instantly

broken dirge
slate swan
#

Well I don't understand what you already have and what you want. Sorry

broken dirge
#

It will still work so no worries ๐Ÿ™‚

broken dirge
slate swan
#

send will have a positional argument defaultly

#

u could say it only takes one and you gave 2

broken dirge
slate swan
#

so you could use an f-string

broken dirge
#

Oh yeah

slate swan
#

!f-strings

unkempt canyonBOT
#

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

broken dirge
#

cool

#

thanks

#

Oh wait. It's not going to work because I need "" In order to eliminate the gaps

slate swan
#

python enables this for you

#

by using ' and "

broken dirge
#

"" ''

#

Yeah, that's what I though

slate swan
#

then do it

broken dirge
#

Yeah, thanks

broken dirge
#

Nice!

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied mute to @rotund nova until <t:1637500172:f> (9 minutes and 59 seconds) (reason: newlines rule: sent 13 consecutive newlines in 10s).

visual yarrow
#

!unmute 796343238839238677

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: pardoned infraction mute for @rotund nova.

visual yarrow
#

Sorry long blocks of code with lots of newlines tend to trip the spam filter.

#

Try this:

rotund nova
#

uh, okay thanks

full valley
#
# !r command button -> Randomly sorts players into teams
@bot.command()
@commands.check(is_issuer_in_dict)
async def randteamchoice(ctx, message, userid):
    if ctx.channel.id in allowed_channels:  # and ctx.author.id in games.values():
        ggid = settings.find_one({"guild_id": ctx.guild.id})
        qsize = ggid["qsize"]
        game_id = ggid["game_id"]
        guild = ctx.guild
        set_aid.add(userid)
        print(len(set_aid))
        if len(set_aid) == qsize / 2:
            set_aid.clear()
            await message.delete()
            print('hell')
            player_ids = games[game_id][:]       -> my code just stops here
            print(player_ids)
            random.shuffle(player_ids)
            print(player_ids)
            team1 = player_ids[:qsize / 2]
            print(team1)
            team1_ids[game_id] = team1
            team2 = player_ids[qsize / 2:]
            print(team1)
            team2_ids[game_id] = team2
            print('hello')
#

Anyone know why its stopping at that line?

#

Its not giving any errors

sullen shoal
shadow wraith
#

where was that

frosty creek
#

sry for disturbing, just wanna ask how to delete a specific data in json file?

#

using a command

shadow wraith
#

kevinlie do you know how to make the bot pin a message

sullen shoal
unkempt canyonBOT
#

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

"hello" was texted by myxi.
frosty creek
#

erm

#

in coding?

shadow wraith
#

yea

#

how do you make the bot pin a message

slate swan
#

get the message object and .pin it

#

!d discord.Message.pin

unkempt canyonBOT
#

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

Pins the message.

You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to do this in a non-private channel context.
frosty creek
#
pin_message(message)```i
shadow wraith
#

oh so it was tha

frosty creek
#

i guess

slate swan
shadow wraith
#

can you show me an example

slate swan
frosty creek
#

oof

sullen shoal
#

!e

d = dict(hi=1)
print(d)
del d["hi"]
print(d)```
unkempt canyonBOT
#

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

001 | {'hi': 1}
002 | {}
slate swan
frosty creek
sullen shoal
#

no

slate swan
#

no

shadow wraith
#

๐Ÿค”

#

i got u homie

#

lemme try that coed

vast gale
#

no, del does not, but message.pin does

frosty creek
#

just go ahead add del main[id] at my code

#

i defined the id btw

sullen shoal
#

also dont use json as a db

frosty creek
#

why

sullen shoal
#

its not meant for that

#

there are plenty of easy databases to choose from

#

which are even easier than json to use

frosty creek
#

for example?

sullen shoal
#

deta

forest spear
#

Can someone help me? Whenever I try to add data in my json file it puts curly brackets automatically here is the code

with open('quote.json','r') as f:
        quote =json.load(f)
        try: 
            for current_user in quote["users"]:
                if current_user['id'] == user:
                    current_user['quote'].append(message)
                    if username != current_user['name']:
                        current_user['name'] = username
                        break
        except:
            quote['users'].append({
                'id':user,
                'name':username,
                'quote': message
            })
            saveJson(quote, "quote.json")โ€Š
sullen shoal
#

an easy solution to this would be to use a database. faster, better, easier to use

forest spear
#

So there is no way to fix it in json?

sullen shoal
#

why would you do that when you dont even need to waste time on it

forest spear
#

Wdym

sullen shoal
#

or you two are different people

#

doing the same thing

slate swan
#
import discord
from discord.ext import commands
import youtube_dl


class music(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.command()
    async def join(self, ctx):
        voice_channel = ctx.author.voice.channel
        if ctx.author.voice is None:
            await ctx.send("shemoajvi vc-shi๐Ÿ˜ ")
        if ctx.voice_client is None:
            await voice_channel.connect()
        else:
            await ctx.voice_client.move_to(voice_channel)

    @commands.command()
    async def disconnect(self, ctx):
        await ctx.voice_client.disconnect()

    @commands.command()
    async def play(self,ctx,url):
        ctx.voice_client.stop()
        FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
        YDL_OPTIONS = {'format':"bestaudio"}
        vc = ctx.voice_client

        with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
            info =  ydl.extract_info(url,download=False)
            url2 = info['formats'][0]['url']
            source = await discord.FFmpeg0pusAudio.from_probe(url2,**FFMPEG_OPTIONS)
            vc.play(source)
    @commands.command()
    async def pause(self,ctx):
        await ctx.voice_client.pause()
        await ctx.send("Paused โธ๏ธ")
    @commands.command()
    async def resume(self,ctx):
        await ctx.voice_client.resume()
        await ctx.send("Resumed โ–ถ๏ธ")

def setup(client): 
    client.add_cog(music(client))

why am i getting invalid syntax error at the end of the code, and yes this is a cog for a music bot

forest spear
#

Wdym

sullen shoal
# forest spear Wdym

if you're really that kind of person who would forever stick with bad stuff like using json as a db, atleast use pickledb

slate swan
#

Hey @sullen shoal how do i add a command upon which saying it teells a quote from a website

sullen shoal
#

fetch it with either httpx.AsyncClient or aiohttp

slate swan
# maiden fable You need an API
def get_quote():
  response = requests.get("SITE")
  json_data = json.loads(response.text)
  quote = json_data[0]['q'] + " -" + json_data[0]['a']
  return(quote)

if msg.startswith('INSPIREUSSR'):
    quote = get_quote()
    await message.channel.send(quote)
sullen shoal
#

replace site with an actual api endpoint

#

and use async library to fetch it

slate swan
#

And don't use requests

sullen shoal
#

just search it online

sullen shoal
#

over 700ms latency

#

and this is something which you should be proud of yourself by doing it without asking for help

slate swan
# slate swan

why is the above like vibrant and below not vibrant? @sullen shoal

sullen shoal
#

basic intendation error, which is taught in the first lesson of every python tutorial

vast gale
#

๐Ÿ˜„

slate swan
#

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

?? what

slate swan
vast gale
#

so it should work now

slate swan
#
import discord
import os
import time
import discord.ext
from discord.utils import get
from discord.ext import commands, tasks
from discord.ext.commands import has_permissions,  CheckFailure, check
from keep_alive import keep_alive

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

@bot.event
async def on_ready():
    await bot.change_presence(status= discord.Status.idle, activity=discord.Game('Nuke Nuke'))
    print("Comrade Ain't Dead") 
    
@bot.event
async def on_message(message):
  if message.author == bot.user:
    return


  if 'i solemnly swear that i am upto no good' in message.content.lower():
    role = discord.utils.get(message.guild.roles, id=904021392998146118)
    await message.author.add_roles(role)
  elif 'mischief managed' in message.content.lower():
    role = discord.utils.get(message.guild.roles, id=904021392998146118)
    await message.author.remove_roles(role)
  await bot.process_commands(message)

def get_quote():
  response = requests.get("https://english.api.rakuten.net/juanroldan1989/api/moviequotes?")
  json_data = json.loads(response.text)
  quote = json_data[0]['q'] + " -" + json_data[0]['a']
  return(quote)

 if msg.startswith('Welp'):
  quote = get_quote()
    
  await message.channel.send(quote)  

@bot.command()
async def say(ctx, *, user_text):
  await ctx.message.delete()
  await ctx.send(user_text)

@bot.command()
async def purge(ctx, amount: int = 5):
  await ctx.channel.purge(limit=amount)  
vast gale
#

the indentation, it needs to be either not in the event, or further up, but the reason its a different color is because vscode is trying to tell you something

#

specifically the indentation of your code.

#

or the location of the definition

#

it would make the most sense to move get quote out of this function defintion

slate swan
#

and anything i can do to import all of these things at once? @vast gale

vast gale
glass rock
#

Can someone pls help im trying to use an API to get image urls. What do i use for asyncronous as module I dont want the bot to freeze by using requests. Also, how do i embed images using only urls?

#

API would be something like thishttps://burgers1.p.rapidapi.com/burgers

sullen shoal
#

i prefer httpx.AsyncClient over aiohttp for some reasons but you can use aiohttp as well

slate swan
#

like json and all of that stuff

sullen shoal
#

idk

#

!d discord.Embed.set_image

unkempt canyonBOT
#

set_image(*, url)```
Sets the image for the embed content.

This function returns the class instance to allow for fluent-style chaining.

Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the image.
sullen shoal
#

use the url parameter

#

to set the image

#

@glass rock

slate swan
sullen shoal
#

for what

glass rock
slate swan
sullen shoal
glass rock
glass rock
sullen shoal
sullen shoal
slate swan
glass rock
glass rock
#

its a small world

slate swan
#

flask tho

sullen shoal
dusk dust
#

can you get this automatic command out of there? Because my bot is prefixed with "/" and if I leave it it's kind of hard to work

slate swan
#

u can change keep alive to anything else

sullen shoal
glass rock
glass rock
sullen shoal
#
def func(*, arg)...
func(arg=1)
#you cant do:
func(1)```
glass rock
#

k ty for the help i figured it out

full valley
#

Myxi would you be able to help for a second Selfie

#
# !r command button -> Randomly sorts players into teams
@bot.command()
@commands.check(is_issuer_in_dict)
async def randteamchoice(ctx, message, userid):
    if ctx.channel.id in allowed_channels:  # and ctx.author.id in games.values():
        ggid = settings.find_one({"guild_id": ctx.guild.id})
        qsize = ggid["qsize"]
        game_id = ggid["game_id"]
        guild = ctx.guild
        set_aid.add(userid)
        print(len(set_aid))
        if len(set_aid) == qsize / 2:
            set_aid.clear()
            await message.delete()
            print('hell')
            player_ids = games[game_id][:]       -> my code just stops here
            print(player_ids)
            random.shuffle(player_ids)
            print(player_ids)
            team1 = player_ids[:qsize / 2]
            print(team1)
            team1_ids[game_id] = team1
            team2 = player_ids[qsize / 2:]
            print(team1)
            team2_ids[game_id] = team2
            print('hello')

My code is stopping in this line, but itโ€™s not giving any errors, and I see nothing wrong with the code

sullen shoal
#

i usually help when the problem is explained properly and i know to solve it

full valley
#

Hard to explain the problem when I donโ€™t know what it is PES2_Shrug

sullen shoal
#

instead of print statements, you can use breakpoint it will basically stop and start a debugger session when it executes that line

#

it helps to debug, try to change value of certain variables and see if it works

full valley
#

It outputs (Pdb)

sullen shoal
#

thats the debugging session

#

check the value of player_ids

#

i dont think it should stop there without any error

#

are you sure youre handling the errors right?

#

the only point it could stop working without any error would be the if statement

stiff nexus
#

how do i get emojis from message.reference.resolved??

hollow briar
maiden fable
#

!d discord.MessageReference.resolved

unkempt canyonBOT
#

The message that this reference resolved to. If this is None then the original message was not fetched either due to the Discord API not attempting to resolve it or it not being available at the time of creation. If the message was resolved at a prior point but has since been deleted then this will be of type DeletedReferencedMessage.

Currently, this is mainly the replied to message when a user replies to a message.

New in version 1.6.

full valley
#

sorry thats my alt.. yeah only have per command errors set up.

#

And not for that command

maiden fable
sullen shoal
stiff nexus
maiden fable
dusk dust
#

o wanted the bot to take the reactions the user sent and turn them into unicode. After that he would react with the same reactions in a set message... is it possible?

maiden fable
#

So like

sullen shoal
#

i think clean_content could work

maiden fable
#

\๐Ÿ…ฐ๏ธ

sullen shoal
#

never tried on emojis tho

maiden fable
#

!d discord.Message.clean_content

unkempt canyonBOT
#

A property that returns the content in a โ€œcleaned upโ€ manner. This basically means that mentions are transformed into the way the client shows it. e.g. <#id> will transform into #name.

This will also transform @everyone and @here mentions into non-mentions.

Note

This does not affect markdown. If you want to escape or remove markdown then use utils.escape_markdown() or utils.remove_markdown() respectively, along with this function.

dusk dust
maiden fable
dusk dust
#

ok

#

thank you:)

full valley
#

still not working

#

and no errors, very strange

sullen shoal
#

are you trying to copy a list

full valley
#

no games is a dictionary

#

id is the key

sullen shoal
#

and whats the value

full valley
#

so im transferring the values from the game_id key to a list

sullen shoal
#

what is the type of value

slate swan
full valley
sullen shoal
#

so its another dict

full valley
#

Well no, thats the games dictionary, with the game id : player id's

slate swan
#

How can I convert the author.name so it's all lower-case?

So
Bero would convert to bero in a Str

sullen shoal
#

so the value is a list and youre trying to copy the values of the list to a new list

sullen shoal
#

list has a method called copy

#

that will do it

full valley
#

right, but its in a dictionary

#

I was unaware you could do that from a list of values in a dict

lone aurora
#
@client.command()
async def role(ctx, role):
    guild = ctx.author.guild
    role1 = discord.utils.get(ctx.author.guild.roles, name= role)
    if role1 not in ctx.author.roles:
        await ctx.author.add_roles(role1)
        await ctx.send(f'Gave Role : **{role}**.')
    elif role1 in ctx.author.roles:
        await ctx.author.remove_roles(role1)
        await ctx.send(f'Took role : **{role}**')
    elif role1 not in guild.roles:
        await ctx.send('No such role exists.')``` The `elif role1 not in guild.roles` isn't working, can anyone tell me what I'm doing wrong

```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'id'``` Error above
sullen shoal
#

the value can be anything

#

an dict, can store any object or instance of something as a value of key

#

maybe even as a key

full valley
slate swan
sullen shoal
unkempt canyonBOT
#

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

[1, 2, 3]
quick gust
#

Name should be as a string

#

@lone aurora

lone aurora
slate swan
quick gust
#

I see

stiff nexus
#

how do i get the last message of a channel?

sullen shoal
full valley
#
player_ids = games[game_id].copy()```
quick gust
#

ignore what I said

lone aurora
#

i just need help with the last elif statement

sullen shoal
full valley
#

wtf is going on angry_floofy_boye

slate swan
lone aurora
#

same error shows up

sullen shoal
lone aurora
#

raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'id'

slate swan
lone aurora
#

i want to make it so that if a non existent role is entered, it would display an error message

slate swan
#

But I'm not sure

lone aurora
#

but is the guild.roles correct?

#

like how do i check if it even exists

lone aurora
#

this should work for it right

guild = ctx.author.guild

if role not in guild.roles:

await ctx.send('This role does not exist.')```
sullen shoal
#

then i would have coded it again

full valley
#

theres no reason it shouldnt be working though

#

theres more verbose bits of code there

#

and that is the bit that isnt working

lone aurora
sullen shoal
lone aurora
#

but i don't want that