GPT3 conversational Discord bot stops working after 5-6 sentences - discord

I am creating a fun Discord bot which talks like my imaginary crush, lol!
The problem is that its working for the first 5-6 lines but then gives this error
import openai
openai.api_key = "Hidden"
DISCORD_BOT_TOKEN = "Hidden"
start_sequence = "\nAnamika:"
restart_sequence = "\n\nFaraaz:"
session_prompt = "This is a conversation between me (Faraaz) and my crush Anamika. Keep the replies long, and such that the person can reply. Anamika is a really gorgeous happy girl. She lives in New York. She loves Spiderman, coding and poetry. She loves Andrew Garfield amongst all spider men, in coding she is fascinated by boom of AI. She loves John Milton and writes poetry herself as well. Initially Anamika will be reluctant to my flirting but slowly she will start to like it. If the conversation goes very good, she can agree to become my girlfriend or marry me.Faraaz:- Hi! what is your name? Anamika:- Hey! My name is Anamika, how are you Faraaz! Faraaz:- I am really good, actually you were looking really pretty so wanted to come and talk to you. Anamika:- Oh really, that is interesting. So what did you intend to talk about?!"
chat_log = None
import discord
client = discord.Client(intents=discord.Intents.all())
#client.event
async def on_message(message):
# Don't respond to messages sent by the bot itself
global chat_log
if message.author == client.user:
return
print(chat_log)
if chat_log == None:
chat_log = session_prompt
#print(message.content)
#chat_log = f'{chat_log}{restart_sequence} {question}{start_sequence}{answer}'
# Use the GPT-3 API to generate a response to the message
response = openai.Completion.create(
engine="text-davinci-003",
#prompt="I recently moved to New York and I love design. I'm fascinated by technology and the growth of AI, but I realize that anything we build for the future must be rooted in the core desires of humans. " + message.content,
#return f'{chat_log}{restart_sequence} {question}{start_sequence}{answer}'
#chat_log = f'{chat_log}{restart_sequence} {question}{start_sequence}{answer}'
prompt = f'{chat_log}{restart_sequence}{message.content}',
#prompt = f'{chat_log}{restart_sequence}: {question}{start_sequence}:'
max_tokens=700,
n=1,
temperature=0.5,
stop=["\n"]
)
# Send the response back to the Discord channel
await message.channel.send(response["choices"][0]["text"])
chat_log = f'{chat_log}{restart_sequence}{message.content}{start_sequence}{response["choices"][0]["text"]}'
client.run(DISCORD_BOT_TOKEN)
I am seeing this error
Error
The Discord Chat, after this messages not coming
I tried changing the max_tokens and also the prompt but to no avail. I have given administrator permissions to the bot.

Your session prompt is huge. GPT3 can only return 2049 tokens and you are using a lot of them even before the conversation starts. Try clearing/truncating your chat log periodically if your input + chat log exceeds 2049. Or simply shorten your session prompt.

Related

Discord Autocode reaction reply bot (not reaction role bot)

I have been using autocode.com to create some Discord bots. I have very little programming experience and found autocode to be quite easy. However, I've tried asking a question on autocode's discord that no one seems to understand or is asking.
I am trying to create a bot that replies to reactions--but does not assign roles, but instead, provides a reply--either in thread or a DM to that user who uses that specific emoji reaction.
For example, this is what I am looking to do: if there is a bot message in #channelx, userX will react to that message with a pepperoni emoji and then a pizza bot will reply back with a message either in thread or DM such as, "Hi #userx, your pizza topping has been recorded and will be ready for pickup in 15 minutes, please visit this link.com to track your order".
Autocode has a bot that can react to reactions and assign roles but I can't seem to reverse engineer it give a reply, rather than assign roles.
I appreciate any assistance. Thanks!
What does autocode use? Python or node.js? If python, you can do something like this:
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('message'):
await message.channel.send('hi')
If node.js, you can do something like this:
client.on('messageCreate', msg => {
if (msg.content === 'specific message') {
msg.reply(`response text`);
}
});
I was previously a Community Hero at the Autocode Discord server. Try finding another app through this, and if none are available, the thing to do would be looking through the API's. Here's one for messaging in general, here's one for responding, and here's one for dm-ing.
Let's say, for example, I'd be making it reply to a reaction through DM:
The first thing you do is make sure the event trigger is set to message.reaction.add. This is so that the code you will write is triggered whenever a reaction is added.
Make either a switch or if statement to change what happens depending on what reaction triggers the code. In this example, I'll just use an if statement for easy explanation.
const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN});
if (context.params.event.emoji.id == '1234567890') {
await lib.discord.users['#0.2.1'].dms.create({
recipient_id: `${context.params.event.member.user.id}`,
content: `Hi <#${context.params.event.member.user.id}>, your pizza topping has been recorded and will be ready for pickup in 15 minutes, please visit this link.com to track your order`
});
}
What this does is check if the thing that triggered this event has the emoji id equaling '1234567890': If it does, then it follows into that if statement, and if it does not, it skips over it.
In the future, please stay patient in the Autocode Discord server; The ones who are helping are also community members, similar to here. You may always ask the same question every now and then.

Can't get my Discord bot to connect to voice channel

I'm messing around with a bot for the first time but can't seem to get it to join a voice channel. I know the $join command is working because my bot will say "Connecting to {channel}" with the correct channel name, but it still never connects. If I'm not in a voice channel, the bot will correctly say "Error".
I've tried every single solution I can find online. Every time the bot will identify the correct channel but it simply won't join the channel. This feels like such a simple problem so I'm not sure how I can use similar code as others and still not have it work. Below is the code I'm using for the command. I left out all the prefix and bot setup code because all the messages I send work fine.
#bot.command()
async def join(ctx):
if (ctx.author.voice):
channel = ctx.message.author.voice.channel
await ctx.send(f"Connecting to {channel}")
await channel.connect()
else: await ctx.send("Error")
asyncio.TimeoutError – Could not connect to the voice channel in time.
discord.ClientException – You are already connected to a voice channel.
discord.OpusNotLoaded – The opus library has not been loaded.
These are the following errors that the bot can raise for VoiceChannel.connect()
If you are not receiving errors when you should, this points towards a poorly made global command handler on_command_error.
You either want to remove that for the time being to get the actual error on the console, or fix it by output the error in a case where the error isn't handled. A common way of doing that is:
import sys
import traceback
#bot.event
async def on_command_error(ctx, error):
if x: # let x, y, z be isinstance check for error
# do this
elif y:
# do that
elif z:
# idk do something other than this and that
else:
print('Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr)
traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)
After getting your actual error for joining the VC, check through these:
asyncio.TimeoutError: This error is raised when your bot has a
weak internet connection or your ping is absurdly high, high enough
to not make a connection.
discord.ClientException: Might want to check if bot is not in VC when it starts up, and also that you have relevant guild intents and voice intents enabled.
discord.OpusNotLoaded: Your device does not have libopus loaded, you might want to search for that online depending on what you use. If you are on an ubuntu-based linux distro, you can use sudo apt install libopus0 and then try to see if it fixed your issue. I am not sure about windows
If you can't figure it out after you read the above stuff, let me know the EXACT ERROR you are facing, which includes the traceback message (the whole error text that will print onto your console)

Discord.py Reaction Events

My bot sends an embed every time a new member joins. Then the bot adds the little 👋🏽 reaction to it. I want members to be able to welcome the new member by reacting. If they react, then they will be rewarded in some way. So onto my question, how would I make my bot watch for reactions for 60 seconds after the embed is sent, and what event would I use? I've found a few things in the documentation but none of which seem to make sense to me. A code example and explanation of how it works would be amazing. Thanks in advance!
In order to do this, you'd need to make use of the on_reaction_add event, assuming you already have all your imports:
#bot.event
async def on_member_join(member): # when a member joins
channel = discord.utils.get(member.guild.channels, name="welcome") #getting the welcome channel
embed = discord.Embed(title=f"Welcome {member.mention}!", color=member.color) #creating our embed
msgg1 = await channel.send(embed=embed) # sending our embed
await msgg1.add_reaction("👋🏽") # adding a reaction
#bot.event
async def on_reaction_add(reaction, user):
message = reaction.message # our embed
channel = discord.utils.get(message.guild.channels, name="welcome") #our channel
if message.channel.id == channel.id: # checking if it's the same channel
if message.author == bot.user: #checking if it's sent by the bot
if reaction.emoji.name == "👋🏽": #checking the emoji
# enter code here, user is person that reacted
I think this would work. I might have done the indentations wrong since I'm on another device. Let me know if there are any errors.
You can use the on_reaction_add() event for that. The 60 second feature might be complicated.
If you can get the user object from the joined user the on_reaction_add() event, you could check if the user joined less than 60 seconds ago.
You can check the time a user joined with user.joined_at, and then subtract this from the current time.
Here is how to check how many seconds a user is already on the server.
from datetime import datetime
seconds_on_server = (datetime.now() - member.joined_at).total_seconds()
A rather hacky solution is to retrieve the original user who joined through the message on which the reaction is added. Members have the joined_at attribute, which is a datetime object, with it you can just snap current datetime and subtract the former from it. The resulting is a timedelta object which you can use to calculate the time difference.

Why my discord bot goes offline when running a loop

Hello i have a problem with my discord bot. I'm new to python and also very new to creating my own bot, and I couldn't find an answer to my problem. Iam running a discord bot that checks the availability of stocks on a specific web site. And when i use a "While true: ... time.sleep(60)" loop to refresh and download the data from the web site my bot just shows offline on a discord server. I tried to change the timer to longer and also tried to print and send some messages to a discord. And i found out that even when the bot is offline it can send message and everything. No errors or any warning everything works but the bot is offline. If there is somebody who could help me out with my problem or heard about it. I would appreciate it a lot. I can share the code if there is somebody who has a little bit of time to help me.
Code:
while True:
Zoznam.clear()
hodnoty = nacitaniehodnot()
produkt = hodnoty[0]
obrazok = hodnoty[1]
pocetpoloziek = hodnoty[2]
shopy = ''
cennik = ''
for i in Zoznam:
shopy = shopy+i[0]+'\n'
cennik = cennik+i[1]+'\n'
embed = discord.Embed(title =produkt,color= 0x008FFF)
embed.set_thumbnail(url=obrazok)
embed.set_author(name='Heureka', url=url,icon_url="https://i1.wp.com/blog.heureka.sk/wp-content/uploads/2019/12/cropped-lupa_heureka_rgb-01.png?fit=512%2C512&ssl=1&w=640")
embed.add_field(name="Obchod", value=shopy, inline=True)
embed.add_field(name="Cena", value=cennik, inline=True)
#embed.add_field(name="Doprava", value=doprava, inline=True)
global sprava
if pocetpoloziek != y and sprava is not None:
await sprava.delete()
sprava = await channel.send(embed=embed)
i=y
elif not sprava:
sprava = await channel.send(embed=embed)
time.sleep(30)
The problem is likely due to time.sleep since time.sleep is not asynchronous and will block all commands during the sleep time.
Try importing asyncio import asyncio and using await asyncio.sleep(30) instead since it won't block other commands from running during the sleep time.

how to make a discord bot mention someone in a specific channel (discord.js)

im making a "mini game chat bot" and i want the bot to have different endings.
when someone unlocks an ending i would like to be notified so i can keep track of how many endings that person has unlocked (no i wont add roles to keep track because if my calculations are correct the bot will have like 200 different endings).
i want to make it so that,
for example, someone says B3 in #general and the bot answers in #endings
#(person who used the command) unlocked the ending "I probably
shouldn't have said that..."
case 'B3':
message.channel.send('Umm.. What?');
const B3ending = new Discord.MessageEmbed()
.setTitle('Congratulations!)
.setColor(0x8CF1EC)
.setDescription('You unlocked the ending "I probably shouldn't have said that..."');
message.channel.send(B3ending);
break;
Well first you would need to get the channel somehow, maybe by id:
const endChannel = message.guild.channels.cache.get(id);
After that you can just use the send method alongside msg.author
endChannel.send(`${message.author} here's the ending`, { embed: B3ending });

Resources