-3

I've been trying to get this guy's bot to work but I really couldn't. Any help is appreciated.

bot.py (original):

import random
import datetime
import discord
from .ai import ChatAI


class ChatBot(discord.Client):
    """ChatBot handles discord communication. This class runs its own thread that
    persistently watches for new messages, then acts on them when the bots username
    is mentioned. It will use the ChatAI class to generate messages then send them
    back to the configured server channel.
    ChatBot inherits the discord.Client class from discord.py
    """

    def __init__(self, maxlines) -> None:
        self.model_name = "355M"  # Overwrite with set_model_name()
        super().__init__()
        self.maxlines = maxlines  #see comment on main.py line 33

    async def on_ready(self) -> None:
        """ Initializes the GPT2 AI on bot startup """
        print("Logged on as", self.user)
        print(self.user.id)
        self.chat_ai = ChatAI(self.maxlines)  # Ready the GPT2 AI generator

    async def on_message(self, message: discord.Message) -> None:
        """ Handle new messages sent to the server channels this bot is watching """
        if message.author == self.user:
            # Skip any messages sent by ourselves so that we don't get stuck in any loops
            return

        # Check to see if bot has been mentioned
        has_mentioned = False
        for mention in message.mentions:
            if str(mention) == self.user.name+"#"+self.user.discriminator:
                has_mentioned = True
                break

        # Only respond randomly (or when mentioned), not to every message
        if random.random() > float(self.response_chance) and has_mentioned == False:
            return

        async with message.channel.typing():
            # Get last n messages, save them to a string to be used as prefix
            context = ""
            # TODO: make limit parameter # configurable through command line args
            history = await message.channel.history(limit=9).flatten()
            history.reverse()  # put in right order
            for msg in history:
                # "context" now becomes a big string containing the content only of the last n messages, line-by-line
                context += msg.content + "\n"
            # probably-stupid way of making every line but the last have a newline after it
            context = context.rstrip(context[-1])
            
            # Print status to console
            print("----------Bot Triggered at {0:%Y-%m-%d %H:%M:%S}----------".format(datetime.datetime.now()))
            print("-----Context for message:")
            print(context)
            print("-----")

            # Process input and generate output
            processed_input = self.process_input(context)
            response = ""
            response = self.chat_ai.get_bot_response(processed_input)
            print("----Response Given:")
            print(response)
            print("----")

            await message.channel.send(response)# sends the response

    def process_input(self, message: str) -> str:
        """ Process the input message """
        processed_input = message
        # Remove bot's @s from input
        return processed_input.replace(("<@!" + str(self.user.id) + ">"), "")

    def set_response_chance(self, response_chance: float) -> None:
        """ Set the response rate """
        self.response_chance = response_chance

    def set_model_name(self, model_name: str = "355M") -> None:
        """ Set the GPT2 model name """
        self.model_name = model_name

It triggers this error:

TypeError: Client.__init__() missing 1 required keyword-only argument: 'intents'

Tried to fix it by changing class definition (line 7) from:

class ChatBot(discord.Client):

to:

class ChatBot(discord.Client(discord.Intents.all())):

but now it's this error:

TypeError: Client.__init__() takes 1 positional argument but 4 were given

I'm very new to python, sorry if I missed something obvious.

CristiFati
  • 38,250
  • 9
  • 50
  • 87
Gaming
  • 3
  • 2
  • 1
    Welcome to Stack Overflow. Please read [ask] and [mre], and make sure to: 1) show a [complete](https://meta.stackoverflow.com/questions/359146/) error message, by copying and pasting, starting from the line that says `Traceback (most recent call last):` until the end; 2) make sure that someone else could **copy and paste** your code into the appropriate files, **without changing anything**, and reproduce the **exact** error that you show. Otherwise we are only guessing. – Karl Knechtel Aug 20 '22 at 10:06
  • Also: Please don't tell us "I did all the research I could". We don't ask you to do [research](https://meta.stackoverflow.com/questions/261592) in order to be worthy of an answer. We ask you to do research in order to *figure out exactly where the question is*, and so that you can *explain* it as clearly as possible. So, *show* us the results of your research, by showing us *specifically what things you tried* to solve the problem, and *what happened* as a result. First, try to figure out the *specific part of the code needed to cause the problem* - again, please read [mre]. – Karl Knechtel Aug 20 '22 at 10:08

1 Answers1

1

I assume that the 1st error is with the original code, while the 2nd is as a result of trying to fix the 1st one.

Let's take the original code:

According to [GitHub]: Rapptz/discord.py - (v2.0.0) discord.py/discord/client.py, Client.__init__() (initializer) signature looks like:

def __init__(self, *, intents: Intents, **options: Any) -> None:

but when invoked by super().__init__() the required intents argument is not supplied, hence the error. In order to properly get rid of it, you have to supply that argument. [PyPI]: discord.py contains some quick samples on how to initialize the bot (and also a documentation URL) that you should check out.

But [GitHub]: johnnymcmike/Gravital - Your Own Personal AI Chatbot has a requirements.txt file, which contains:

discord.py==1.7.3

and from [GitHub]: Rapptz/discord.py - (v1.7.3) discord.py/discord/client.py, the initializer signature is:

def __init__(self, *, loop=None, **options):

which is exactly what you need.

You must install the packages (with the exact versions) in that file (pip install -r requirements.txt). Check [SO]: How can I install packages using pip according to the requirements.txt file from a local directory? or [PyPA.PIP]: User Guide for more details (you could also check [SO]: How to install a package for a specific Python version on Windows 10? (@CristiFati's answer) for more generic package installation problems that may arise).

Note: based on the original error fix attempt, one could easily notice that Python programming XP level is not very high, and in this situation you should stick with the recommendations and defaults (and also read the docs), otherwise you'll end up in situations like this one.

CristiFati
  • 38,250
  • 9
  • 50
  • 87