首页 > 解决方案 > How can I make a bot not case sensitive in discord.py?

问题描述

This includes prefixes and commands and pretty much anything you type into in Discord. Here is my code:

from discord.ext import commands
import discord.member
from dotenv import load_dotenv
import discord
from discord.utils import get

bot = commands.Bot(command_prefix="bot ")
TOKEN = "4893285903457897349857938275732985" #not a valid token by the way :)

@bot.event
async def on_ready():
    print(f'{bot.user} has connected to Discord!')


@bot.command(name='image', help='Example command')
async def image(ctx):
    #code for function goes here
    pass


bot.run(TOKEN)

标签: pythonpython-3.xdiscord.py

解决方案


Bot commands can be case insensitive however there is no feature in discord.py to make prefixes case insensitive. However, there is a way to work around this.

Making bot commands case insensitive

Change bot = commands.Bot(command_prefix="prefix!")

to: bot = commands.Bot(case_insensitive=True, command_prefix="prefix!")

Making prefixes case insensitive

I honestly don't really recommend this but if you really need case insensitive prefixes, follow the code below

Create a function called mixedCase()

def mixedCase(*args):
  """
  Gets all the mixed case combinations of a string

  This function is for in-case sensitive prefixes
  """
  total = []
  import itertools
  for string in args:
    a = map(''.join, itertools.product(*((c.upper(), c.lower()) for c in       string)))
    for x in list(a): total.append(x)

  return list(total)

Now modify bot = commands.Bot(command_prefix="prefix!")

to bot = commands.Bot(command_prefix=mixedCase("prefix!"))

The final code

from discord.ext import commands
import discord.member
from dotenv import load_dotenv
import discord
from discord.utils import get

def mixedCase(*args):
  """
  Gets all the mixed case combinations of a string

  This function is for in-case sensitive prefixes
  """
  total = []
  import itertools
  for string in args:
    a = map(''.join, itertools.product(*((c.upper(), c.lower()) for c in string)))
    for x in list(a): total.append(x)

  return list(total)

bot = commands.Bot(case_insensitive=True, command_prefix=mixedCase("prefix" ))
TOKEN = "4893285903457897349857938275732985" #not a valid token by the way :)

@bot.event
async def on_ready():
    print(f'{bot.user} has connected to Discord!')


@bot.command(name='image', help='Example command')
async def image(ctx):
    #code for function goes here
    pass


bot.run(TOKEN)


推荐阅读