运行Gravital Discord ML聊天Bot遇TypeError:缺少intents参数
问题
启动Gravital这款Discord机器学习聊天Bot时,运行main.py触发以下错误:
File "D:\Gravital-master\Bot\bot.py", line 19, in __init__ super().__init__() TypeError: __init__() missing 1 required keyword-only argument: 'intents'
main.py本身运行正常,但调用bot.py时出现问题。尝试更新疑似过时的代码未解决,相关代码如下:
bot.py代码
import random import datetime import discord from .ai import ChatAI from discord.ext import commands 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 """ intents = discord.Intents.all() bot = commands.Bot(command_prefix='.',intents=intents) 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
main.py代码
#!/usr/bin/env python3 import argparse from Bot.bot import ChatBot from Bot.ai import ChatAI def main(): """Main function""" parser = argparse.ArgumentParser(description="Amalgam") parser.add_argument("--token", dest="MTA3MjMyNDc3OTgyODMxODIyOA.GKZNRE.1Wjpz1KPDzN6HohbaptBmYux-wzdU10u6DRKVM", help="Your discord bot's token. Required for launching the bot in non-test mode!") parser.add_argument("--response_chance", dest="response_chance", default=1, help="How likely the bot is to respond to a message in which it is not pinged. For example: give 0.25 for a 25%% chance, give 0 for no random responses. Defaults to 0.") parser.add_argument("--test", dest="test", action="store_true", help="Test model by talking to the AI right in the terminal.") parser.add_argument("--maxlines", dest="maxlines", help="The maximum number of lines that the AI will try to generate per message. Will always generate random amount up to this value, which defaults to 1.", default=1) parser.add_argument("--train", dest="train", action="store_true", help="Trains the model on a file named dataset.txt. Only use this if you have a good NVIDIA GPU. Overwrites existing trained_model folder. Currently untested!") args = parser.parse_args() if args.test: ai = ChatAI(args.maxlines) # see comment on line 33 print("Type \"exit!!\" to exit.") while True: inp = input("> ") if(inp == "exit!!"): return print(ai.get_bot_response(message=inp)) elif args.train: from aitextgen import aitextgen #lazily import aitextgen. idk if this matters, but i thought it might speed up start times for when you're not training the AI as opposed to having this at the top ai = aitextgen(to_gpu=True) ai.train("dataset.txt", line_by_line=False, from_cache=False, num_steps=55000, #Takes less than an hour on my RTX 3060. Increase if you want, but remember that training can pick up where it left off after this finishes. generate_every=1000, save_every=1000, learning_rate=1e-3, fp16=True, #this setting improves memory efficiency, disable if it causes issues batch_size=2, ) else: # probably a cleaner way to do this than to pass the maxlines param all the way through? submit PR if you know client = ChatBot(args.maxlines) client.set_response_chance(args.response_chance) if args.token is None: raise Exception( "You are trying to launch the bot but have not included your discord bot's token with --token. Please include this and try again.") client.run(args.token) if __name__ == "__main__": main()
解决方案
错误根源是discord.py v2.0+版本强制要求实例化discord.Client时必须传入intents参数,原代码虽定义了intents类属性,但父类初始化时未传递该参数。另外代码中冗余定义的commands.Bot实例完全无用,可直接删除。
修改步骤
- 修改bot.py
- 删除冗余行
bot = commands.Bot(command_prefix='.',intents=intents) - 将父类初始化代码
super().__init__()改为super().__init__(intents=self.intents),传递定义好的intents参数
- 删除冗余行
修改后的bot.py代码:
import random import datetime import discord from .ai import ChatAI from discord.ext import commands 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 """ intents = discord.Intents.all() def __init__(self, maxlines) -> None: self.model_name = "355M" # Overwrite with set_model_name() super().__init__(intents=self.intents) 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
- 修复main.py的参数错误
原代码中parser.add_argument("--token")的dest参数设置错误,导致无法正确获取传入的token值,修改为:
parser.add_argument("--token", dest="token", help="Your discord bot's token. Required for launching the bot in non-test mode!")
内容的提问来源于stack exchange,提问作者feelbits
相关产品推荐
相关产品推荐

