epiKubuntu
epiKubuntu

Reputation: 11

Can I use classes instead of all these if statements? Discord python bot

I have this question about classes/if statements.

I have this code with a lot of if statements that looks like this:

if message.content.lower().startswith("test"):
        time.sleep(1)
        await message.add_reaction(gEmoji)
        await message.add_reaction(aEmoji)
        await message.add_reaction(yEmoji)

But all for different words and emojis.

This is my short version of my code:

import discord
import random
from discord.ext.commands import Bot
from discord.ext import commands
import sys
import os
import cogs
import config
import logging
import asyncio
import datetime
import time

client = discord.Client()
client = commands.Bot(command_prefix='*')

gEmoji = "🇬"
aEmoji = "🇦"
yEmoji = "🇾"

hEmoji = "🇭"
oEmoji = "🇴"
tEmoji = "🇹"

@client.event
async def on_message(message):
    if message.content.lower().startswith("test"):
        time.sleep(1)
        await message.add_reaction(gEmoji)
        await message.add_reaction(aEmoji)
        await message.add_reaction(yEmoji)

    if message.content.startswith("hot"):
        time.sleep(1)
        await message.add_reaction(hEmoji)
        await message.add_reaction(oEmoji)
        await message.add_reaction(tEmoji)


client.run("TOKEN/CENSORED")

In my version of this code I have ~200 lines of code and ~150 of them are only if statements.

As I'm new to Python and just started using classes, I was wondering if somehow I can change the if statements to use classes to get a better looking code, and a easier to understand code.

Upvotes: 0

Views: 126

Answers (1)

Błotosmętek
Błotosmętek

Reputation: 12927

You could probably use classes if you wish to, but that makes very little sense to me. What makes sense is to use dictionaries and lists:

words = { "gay": [ "🇬", "🇦", "🇾" ],
          "hot": [ "🇭", "🇴", "🇹" ]
          # add other words as necessary
        }

@client.event
async def on_message(message):
    for word, emojis in words.items():
        if message.content.lower().startswith(word):
            time.sleep(1)
            for emoji in emojis:
                await message.add_reaction(emoji)
            break

That's the whole function, no need for hundreds of ifs. Note: I added a break to exit the outer for loop under assumption that no word is a prefix of another, so for example there's no "hotter" in your dictionary if there's "hot" in it. If this assumption is wrong, break should be removed and the words should be sorted longest-first.

Upvotes: 1

Related Questions