Make code uncaseSensitive, Python, Discord Bot - python

How can i make this code icaseSensitive? I have tried bot = commands.Bot(command_prefix=';', case_insensitive=True
Is the code i have here on the rewrite branch? I know how on async def on_message but have heard it is not that smart to use async def on_message
Code:
import discord
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
bot = commands.Bot(command_prefix=';', case_insensitive=True)
#bot.command(pass_context=True)
#commands.has_role("Admin")
async def info(ctx, user: discord.Member):
embed = discord.Embed(title="{}'s info:".format(user.name), description="Here is his description. Bounty is around 1000 Dubloons", color=0x00ff00)
embed.add_field(name="Navn", value=user.name, inline=True)
embed.add_field(name="ID", value=user.id, inline=True)
embed.add_field(name="Status", value=user.status, inline=True)
embed.add_field(name="Høyeste rolle", value=user.top_role)
embed.add_field(name="Ble med", value=user.joined_at)
embed.set_thumbnail(url=user.avatar_url)
await bot.say(embed=embed)
edit:
from itertools import product
def aliases(info):
return [''.join(item) for item in product(*((c.lower(), c.upper()) for c in info))]
#bot.command(pass_context=True, aliases=aliases('info'))
#commands.has_role("Admin")
async def info(ctx, user: discord.Member):
embed = discord.Embed(title="{}'s info:".format(user.name), description="Here is his description. Bounty is around 1000 Dubloons", color=0x00ff00)
embed.add_field(name="Navn", value=user.name, inline=True)
embed.add_field(name="ID", value=user.id, inline=True)
embed.add_field(name="Status", value=user.status, inline=True)
embed.add_field(name="Høyeste rolle", value=user.top_role)
embed.add_field(name="Ble med", value=user.joined_at)
embed.set_footer(text="© Solmester123456 // Thomas")
embed.set_thumbnail(url=user.avatar_url)
await bot.say(embed=embed)

Try running import discord; print(discord.__version__). The rewrite branch is 1.0, the async branch is 0.16. I suspect you're on the async branch.
A stopgap solution would be to register every mixed capitlization as an alias, something like
from itertools import product
def aliases(word):
variations = (''.join(item) for item in product(*((c.lower(), c.upper()) for c in word)))
return [item for item in variations if item != word]
# registering the name of the coroutine as an alias causes it to fail
#bot.command(pass_context=True, aliases=aliases('info'))
#commands.has_role("Admin")
async def info(ctx, user: discord.Member):
...
Edit: This was previously not working because product returns tuples instead of strings, so we need to join them to make words.

Related

Command does not work during discord bot creation

I typed !mycommand2 [name] [role] because it didn't come out even when I typed command !캐릭터생성 [name] [role], but it's still the same. Why? And description's role(Is it like an annotation? Explain to the developer what command this is without a role?) and...I also wonder about command hidden.
char = I want to mack a instance.....char.py has class char.
import discord, asyncio
import char
from discord.ext import commands
intents=discord.Intents.all()
client = discord.Client(intents=intents)
bot = commands.Bot(command_prefix='!',intents=intents,help_command=None)
#client.event
async def on_ready():
await client.change_presence(status=discord.Status.online, activity=discord.Game("언성듀엣!"))
#bot.command(name="테스트", description="테스트용 함수", hidden=False) #set hidden to True to hide it in the help
async def mycommand1(ctx, argument1, argument2):
await ctx.channel.send ("{} | {}, Hello".format(ctx.author, ctx.author.mention))
await ctx.author.send ("{} | {}, User, Hello".format(ctx.author, ctx.author.mention))
char_num = 1
#bot.command(name="캐릭터생성", description="테스트용 함수", hidden=False) #set hidden to True to hide it in the help
async def mycommand2(ctx, context1, context2):
global char_num
globals()['char_{}'.format(char_num)]=char(name=context1,Sffter=context2,username=ctx.author.name)
char_num+=1
await ctx.message.channel.send ("done", context1,"!")
client.run('-')
Change the function name to the command name
async def urcommandname(ctx,arg1,arg2):

Auto role in discord.py

I checked all codes what I can find but they don't work with my bot.What am I doing wrong?
They’re not much different and they all work, but not in my code. No mistakes in the cmd.
my friend can’t do it either. Bot has administrator privileges (I checked)
role = "NEWS"
#bot.event
async def on_member_join(member):
rank = discord.utils.get(member.guild.roles, name=role)
await member.add_roles(rank)
print(f"{member} was given the {rank} role.")
Second
#bot.event
async def on_member_join( member ):
role = discord.utils.get( member.guild.roles, id = 889869064997068810)
await member.add_roles( role )
Third
#bot.event
async def on_member_join(member):
role = discord.utils.get(member.guild.roles, name='Unverified')
await member.add_roles(role)
All code without this auto role
import random
import json
import discord
import datetime
from lol import an
from zdar import answer_hello
from zdar import hello_words
from zdar import maternie
from zdar import answer_maternie
from discord.ext import commands
from config0 import settings
bot = commands.Bot(command_prefix= settings['prefix'])
bot.remove_command('help')
#bot.command()
async def clear(ctx, amount = 100):
await ctx.channel.purge( limit = amount )
#bot.command()
async def hello(ctx):
await ctx.send(f',{ctx.message.author.mention}!')
#bot.command()
async def cat(ctx):
await ctx.send(random.choice(an))
#bot.command()
async def time (ctx):
emb = discord.Embed(title = 'Титульник', colour = discord.Color.green(), url = 'https://www.timeserver.ru/cities/by/minsk')
emb.set_author(name = bot.user.name, icon_url = bot.user.avatar_url)
emb.set_footer ( text = ctx.author.name, icon_url= ctx.author.avatar_url)
emb.set_image( url= 'https://i.pinimg.com/originals/3f/82/40/3f8240fa1d16d0de6d4e7510b43b37ba.gif')
emb.set_thumbnail( url= 'https://static.wikia.nocookie.net/anime-characters-fight/images/9/90/Eugo_La_Raviaz_mg_main.png/revision/latest/scale-to-width-down/700?cb=20201114130423&path-prefix=ru')
now_date = datetime.datetime.now()
emb.add_field( name = 'Time', value='Time:{}'.format( now_date))
await ctx.send(embed = emb)
bot.run(settings['token'])
You have to specify the member intent to receive on_member_join events. You can do this while creating your bot object by adding an intent option:
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix=settings['prefix'], intents=intents)
Note
If your bot is verified you require the SERVER MEMBERS INTENT which you can request on the bot page of your application.

Taking away all of persons roles and giving them back after some time

I am trying to make a bot that once given a command will take away a persons roles and give them back after a certain amount of time. right now im getting the eror unexpected indent.
here is the code:
import discord
from discord.ext import commands
import ctx
import re
import time
from time import sleep
from discord.ext import rolelist, roles, role
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as', self.user)
async def on_message(self, message):
if message.author == self.user:
return
messageContent = message.content
if len(messageContent) > 0:
if re.search("^send.*court$", messageContent):
user_id = message.mentions[0].id
user = message.mentions[0]
await message.channel.send(
f"sending <#{user_id}> to court!"
)
async def listroles(ctx):
user_roles = [role.mention for role in ctx.message.author.roles if role.mentionable]
await message.channel.send(user_roles)
async def roles(ctx):
print(", ".join([str(r.id) for r in ctx.guild.roles]))
role = discord.utils.get(message.guild.roles, name="Jail")
await user.add_roles(role)
async def roles(user.roles):
rolelist = [r.mention for r in user.roles if r != ctx.guild.default_role]
roles = ", ".join(rolelist)
print(rolelist)
client = MyClient()
client.run('TOKEN_GOES_HERE')
Python don't use {} like C# or Java, it works with indentation. So your code should be this:
await user.add_roles(role)
async def get_roles(user):
rolelist = [r.mention for r in user.roles if r != ctx.guild.default_role]
roles = ", ".join(rolelist)
print(rolelist)

How can I edit embed with emoji buttons in discord.py?

How can I edit embed with emoji buttons in discord.py?
I was making it like this.. but it doesn't works..
#client.event
async def on_message(message):
if message.content.startswith("!menu"):
embed=discord.Embed(color=0x00FFFF, title=f'Menu', description= f'🔴 - test1 \n🟠 - test2 \n🟡 - test3 \n🟢 - test4 \n🔵 - test5 \n🟣 - test6', timestamp=message.created_at)
embed.set_footer(text=f'-', icon_url=message.author.avatar_url)
msg = await message.channel.send(embed=embed)
await msg.add_reaction('🔴')await msg.reaction_add('🟠')
await msg.add_reaction('🟡')
await msg.add_reaction('🟢')
await msg.add_reaction('🔵')
await msg.add_reaction('🟣')
if str(msg.add_reaction) == '🔴':
embed1=discord.Embed(color=0x00FFFF, title=f'edit1', description= f'test1')
await msg.edit(embed=embed1)
I want some edit codes!!
Welcome to StackOverflow, you can use discord.ext.menus. Here's how you need to install it.
pip install git+https://github.com/Rapptz/discord-ext-menus.
Then you can do something like this.
import discord
from discord.ext import menus
class ColorMenu(menus.Menu):
def __init__(self, embed):
super().__init__(timeout=30.0, delete_message_after=True)
self.embed = embed
self.result = None
async def send_initial_message(self, ctx, channel):
return await channel.send(embed=self.embed)
#menus.button('🔴')
async def red_button(self, payload):
# do what ever you want with this.
# right now I'm going to just edit the message
self.embed.description = 'test1'
self.embed.title = 'title1'
self.message.edit(embed=self.embed)
# do the same thing for other reactions
Then make a new command and instantiate the class, like this:
#bot.command()
async def menu(ctx):
color_menu = ColorMenu()
color_menu.start(ctx)
And you're done.
Good luck with your bot.

Multiple Choice Reaction python (discord.py)

I'm trying to do a multiple choice button / reaction in discord using python (discord.py) -- something similar to the image below:
For example when it reacts to 2️⃣, that shows page 2, when it reacts to 3️⃣, that shows page 3 ...
Could anyone help me, please?
import discord
from discord.ext import commands
class Wiki(commands.Cog):
def __init__(self,bot):
self.bot=bot
#commands
#commands.command(name="wiki",aliases=["w"])
async def wiki(self,ctx):
page1=discord.Embed(
title='Page 1/3',
description='Description1',
colour=discord.Colour.orange()
)
page2=discord.Embed(
title='Page 2/3',
description='Description2',
colour=discord.Colour.orange()
)
page3=discord.Embed(
title='Page 3/3',
description='Description3',
colour=discord.Colour.orange()
)
pages=[page1,page2,page3]
message= await ctx.send(embed=page1)
await message.add_reaction('1️⃣')
await message.add_reaction('2️⃣')
await message.add_reaction('3️⃣')
emoji=""
if emoji=="1️⃣":
await message.edit_message(message,embed=pages[0])
if emoji=="2️⃣":
await message.edit_message(message,embed=pages[1])
if emoji=="3️⃣":
await message.edit_message(message,embed=pages[2])
def setup(bot):
bot.add_cog(Wiki(bot))
Take a look at the documentation for wait_for, which is how you should treat this kind of case. I won't spoonfeed you the code though, you should give it a fair shot yourself first.
Also, discord.py already has something built-in for embeds that change pages automatically based on reactions called menus, so it'll probably be easier to just use that instead of re-implementing it yourself.
Answering my own question.
I know it's not the best answer, but it works XD.
Any suggestion will be well accepted. Thank you all so much for your help.
import asyncio
import discord
from discord.ext import commands
class Wiki(commands.Cog):
def __init__(self,bot):
self.bot=bot
#commands
#commands.command(name="wiki",aliases=["w"])
async def wiki(self,ctx):
first_run = True
while True:
if first_run:
page1=discord.Embed(title='Page 1/3',description='Description1',colour=discord.Colour.orange())
first_run=False
msg = await ctx.send(embed=page1)
reactmoji = ["1️⃣","2️⃣","3️⃣"]
for react in reactmoji:
await msg.add_reaction(react)
def check_react(reaction, user):
if reaction.message.id != msg.id:
return False
if user != ctx.message.author:
return False
if str(reaction.emoji) not in reactmoji:
return False
return True
try:
res, user = await self.bot.wait_for('reaction_add', check=check_react)
except asyncio.TimeoutError:
return await msg.clear_reactions()
if user != ctx.message.author:
pass
elif '1️⃣' in str(res.emoji):
print('<<1️⃣>>')
await msg.remove_reaction("1️⃣",user)
await msg.edit(embed=page1)
elif '2️⃣' in str(res.emoji):
print('<<2️⃣>>')
page2=discord.Embed(title='Page 2/3',description='Description2',colour=discord.Colour.orange())
await msg.remove_reaction("2️⃣",user)
await msg.edit(embed=page2)
elif '3️⃣' in str(res.emoji):
print('<<3️⃣>>')
page3=discord.Embed(title='Page 3/3',description='Description3',colour=discord.Colour.orange())
await msg.remove_reaction("3️⃣",user)
await msg.edit(embed=page3)
def setup(bot):
bot.add_cog(Wiki(bot))

Categories

Resources