small formatting changes

This commit is contained in:
Aaron Crate 2023-11-17 19:03:31 +00:00
parent 7a536a9cfb
commit a772460827
3 changed files with 248 additions and 248 deletions

View File

@ -1,244 +1,245 @@
import os import os
import json import json
import config import config
import openai import openai
import aiohttp import aiohttp
import asyncio import asyncio
import discord import discord
import requests import requests
import random import random
from openai import AsyncOpenAI from openai import AsyncOpenAI
from datetime import datetime from datetime import datetime
from collections import defaultdict from collections import defaultdict
from operator import itemgetter from operator import itemgetter
intents = discord.Intents.default() openaikey = config.OPENAI_TOKEN
intents.members = True gapikey = config.GIF_TOKEN
intents.messages = True garfkey = config.GARFBOT_TOKEN
intents.message_content = True
client = discord.Client(intents=intents) intents = discord.Intents.default()
intents.members = True
openaikey = config.OPENAI_TOKEN intents.messages = True
gapikey = config.GIF_TOKEN intents.message_content = True
garfkey = config.GARFBOT_TOKEN client = discord.Client(intents=intents)
@client.event @client.event
async def on_ready(): async def on_ready():
asyncio.create_task(process_image_requests()) asyncio.create_task(process_image_requests())
print(f"Logged in as {client.user.name} running gpt-3.5-turbo.", flush=True) print(f"Logged in as {client.user.name} running gpt-3.5-turbo.", flush=True)
# MeowCounts File # MeowCounts File
counts_file = "meow_counts.json" counts_file = "meow_counts.json"
meow_counts = defaultdict(int) meow_counts = defaultdict(int)
if os.path.isfile(counts_file): if os.path.isfile(counts_file):
with open(counts_file, "r") as f: with open(counts_file, "r") as f:
meow_counts.update(json.load(f)) meow_counts.update(json.load(f))
elif os.path.exists(counts_file): elif os.path.exists(counts_file):
with open(counts_file, "r") as f: with open(counts_file, "r") as f:
meow_counts = json.load(f) meow_counts = json.load(f)
try: try:
with open("user_stats.json", "r") as f: with open("user_stats.json", "r") as f:
user_stats = json.load(f) user_stats = json.load(f)
except FileNotFoundError: except FileNotFoundError:
user_stats = {} user_stats = {}
# GarfChats # GarfChats
async def generate_chat_response(question): async def generate_chat_response(question):
try: try:
client = AsyncOpenAI(api_key = openaikey) client = AsyncOpenAI(api_key = openaikey)
response = await client.chat.completions.create( response = await client.chat.completions.create(
model="gpt-3.5-turbo", model="gpt-3.5-turbo",
messages=[ messages=[
{"role": "system", "content": "Pretend you are sarcastic Garfield."}, {"role": "system", "content": "Pretend you are sarcastic Garfield."},
{"role": "user", "content": f"{question}"} {"role": "user", "content": f"{question}"}
], ],
max_tokens=400 max_tokens=400
) )
answer = response.choices[0].message.content answer = response.choices[0].message.content
return answer.replace("an AI language model", "a cartoon animal") return answer.replace("an AI language model", "a cartoon animal")
except openai.BadRequestError as e: except openai.BadRequestError as e:
return f"`GarfBot Error: {e}`" return f"`GarfBot Error: {e}`"
except openai.APIError as e: except openai.APIError as e:
print(e, flush=True) print(e, flush=True)
return f"`GarfBot Error: Monday`" return f"`GarfBot Error: Monday`"
except Exception as e: except Exception as e:
print(e, flush=True) print(e, flush=True)
return f"`GarfBot Error: Lasagna`" return f"`GarfBot Error: Lasagna`"
# GarfPics # GarfPics
async def generate_image(prompt): async def generate_image(prompt):
try: try:
client = AsyncOpenAI(api_key = openaikey) client = AsyncOpenAI(api_key = openaikey)
response = await client.images.generate( response = await client.images.generate(
model="dall-e-3", model="dall-e-3",
prompt=prompt, prompt=prompt,
n=1, n=1,
size="1024x1024" size="1024x1024"
) )
image_url = response.data[0].url image_url = response.data[0].url
return image_url return image_url
except openai.BadRequestError as e: except openai.BadRequestError as e:
return f"`GarfBot Error: ({e.status_code}) - Your request was rejected as a result of our safety system.`" return f"`GarfBot Error: ({e.status_code}) - Your request was rejected as a result of our safety system.`"
except openai.InternalServerError as e: except openai.InternalServerError as e:
print(e, flush=True) print(e, flush=True)
return f"`GarfBot Error: {e.status_code} - Monday`" return f"`GarfBot Error: {e.status_code} - Monday`"
except Exception as e: except Exception as e:
print(e, flush=True) print(e, flush=True)
return f"`GarfBot Error: Lasagna`" return f"`GarfBot Error: Lasagna`"
image_request_queue = asyncio.Queue() image_request_queue = asyncio.Queue()
async def process_image_requests(): async def process_image_requests():
async with aiohttp.ClientSession() as session: async with aiohttp.ClientSession() as session:
while True: while True:
request = await image_request_queue.get() request = await image_request_queue.get()
message = request['message'] message = request['message']
prompt = request['prompt'] prompt = request['prompt']
image_url = await generate_image(prompt) image_url = await generate_image(prompt)
if "GarfBot Error" not in image_url: if "GarfBot Error" not in image_url:
async with session.get(image_url) as resp: async with session.get(image_url) as resp:
if resp.status == 200: if resp.status == 200:
image_data = await resp.read() image_data = await resp.read()
timestamp = message.created_at.strftime('%Y%m%d%H%M%S') timestamp = message.created_at.strftime('%Y%m%d%H%M%S')
filename = f"images/{timestamp}_generated_image.png" filename = f"images/{timestamp}_generated_image.png"
with open(filename, "wb") as f: with open(filename, "wb") as f:
f.write(image_data) f.write(image_data)
with open(filename, "rb") as f: with open(filename, "rb") as f:
await message.channel.send(file=discord.File(f)) await message.channel.send(file=discord.File(f))
else: else:
await message.channel.send("`GarfBot Error: Odie`") await message.channel.send("`GarfBot Error: Odie`")
else: else:
await message.channel.send(image_url) await message.channel.send(image_url)
image_request_queue.task_done() image_request_queue.task_done()
await asyncio.sleep(2) await asyncio.sleep(2)
# Listen for messages # Listen for messages
@client.event @client.event
async def on_message(message): async def on_message(message):
if message.author == client.user: if message.author == client.user:
return return
if message.content.lower().startswith("hey garfield") or isinstance(message.channel, discord.DMChannel): if message.content.lower().startswith("hey garfield") or isinstance(message.channel, discord.DMChannel):
question = message.content[12:] if message.content.lower().startswith("hey garfield") else message.content question = message.content[12:] if message.content.lower().startswith("hey garfield") else message.content
answer = await generate_chat_response(question) answer = await generate_chat_response(question)
await message.channel.send(answer) await message.channel.send(answer)
if message.content.lower().startswith('garfpic '): if message.content.lower().startswith('garfpic '):
user = message.author.name user = message.author.name
server = message.guild.name if message.guild else "Direct Message" server = message.guild.name if message.guild else "Direct Message"
prompt = message.content[8:] prompt = message.content[8:]
print(f"Image Request - User: {user}, Server: {server}, Prompt: {prompt}", flush=True) print(f"Image Request - User: {user}, Server: {server}, Prompt: {prompt}", flush=True)
await message.channel.send(f"`Please wait... image generation queued: {prompt}`") await message.channel.send(f"`Please wait... image generation queued: {prompt}`")
await image_request_queue.put({'message': message, 'prompt': prompt}) await image_request_queue.put({'message': message, 'prompt': prompt})
if message.content.lower() == "lasagna": if message.content.lower() == "lasagna":
await send_gif(message, "garfield lasagna") await send_gif(message, "garfield lasagna")
if message.content.lower() == "monday": if message.content.lower() == "monday":
await send_gif(message, "garfield monday") await send_gif(message, "garfield monday")
if message.content.lower().startswith("garfgif "): if message.content.lower().startswith("garfgif "):
search_term = message.content[8:] search_term = message.content[8:]
await send_gif(message, search_term) await send_gif(message, search_term)
if message.guild and message.guild.id == 719605634772893757: # Army of Dawn Server
if message.guild and message.guild.id == 719605634772893757:
if "meow" in message.content.lower():
print(f"Meow detected: {message.content}") if "meow" in message.content.lower():
print(f"Meow detected: {message.content}")
meow_counts[str(message.author.id)] += 1
meow_counts[str(message.author.id)] += 1
with open(counts_file, "w") as f:
json.dump(dict(meow_counts), f) with open(counts_file, "w") as f:
json.dump(dict(meow_counts), f)
if message.content.lower() == "meowcount":
response = f"My records show that <@{message.author.id}> has meowed {meow_counts[str(message.author.id)]} time(s). Have a nice day." if message.content.lower() == "meowcount":
await message.channel.send(response) response = f"My records show that <@{message.author.id}> has meowed {meow_counts[str(message.author.id)]} time(s). Have a nice day."
await message.channel.send(response)
if message.content.lower() == "top meowers":
top_meowers = sorted(meow_counts.items(), key=itemgetter(1), reverse=True)[:10] if message.content.lower() == "top meowers":
embed = discord.Embed(title="Top Meowers :cat:", color=0x000000) top_meowers = sorted(meow_counts.items(), key=itemgetter(1), reverse=True)[:10]
for i, (user_id, meow_count) in enumerate(top_meowers): embed = discord.Embed(title="Top Meowers :cat:", color=0x000000)
user = await client.fetch_user(int(user_id)) for i, (user_id, meow_count) in enumerate(top_meowers):
embed.add_field(name=f"{i+1}. {user.name}", value=f"{meow_count} meows", inline=False) user = await client.fetch_user(int(user_id))
await message.channel.send(embed=embed) embed.add_field(name=f"{i+1}. {user.name}", value=f"{meow_count} meows", inline=False)
await message.channel.send(embed=embed)
if message.content.lower() == "checking in":
# Check if user has already checked in if message.content.lower() == "checking in":
user_id = str(message.author.id) # Check if user has already checked in
if user_id in user_stats and user_stats[user_id]["check_in_time"] is not None: user_id = str(message.author.id)
await message.channel.send(f"{message.author.mention} You are already checked in. Please check out first.") if user_id in user_stats and user_stats[user_id]["check_in_time"] is not None:
return await message.channel.send(f"{message.author.mention} You are already checked in. Please check out first.")
return
# Record check-in time and add user to user_stats if not already there
check_in_time = datetime.utcnow().timestamp() # Record check-in time and add user to user_stats if not already there
if user_id not in user_stats: check_in_time = datetime.utcnow().timestamp()
user_stats[user_id] = {"check_ins": 0, "total_time": 0, "check_in_time": None} if user_id not in user_stats:
user_stats[user_id]["check_in_time"] = check_in_time user_stats[user_id] = {"check_ins": 0, "total_time": 0, "check_in_time": None}
await message.channel.send(f"{message.author.mention} You have been checked in. Please mute your microphone.") user_stats[user_id]["check_in_time"] = check_in_time
await message.channel.send(f"{message.author.mention} You have been checked in. Please mute your microphone.")
elif message.content.lower() == "checking out":
# Check if user has already checked in elif message.content.lower() == "checking out":
user_id = str(message.author.id) # Check if user has already checked in
if user_id not in user_stats or user_stats[user_id]["check_in_time"] is None: user_id = str(message.author.id)
await message.channel.send(f"{message.author.mention} You have not checked in yet. Please check in first.") if user_id not in user_stats or user_stats[user_id]["check_in_time"] is None:
return await message.channel.send(f"{message.author.mention} You have not checked in yet. Please check in first.")
return
# Record check-out time and update user stats
check_out_time = datetime.utcnow().timestamp() # Record check-out time and update user stats
check_in_time = user_stats[user_id]["check_in_time"] check_out_time = datetime.utcnow().timestamp()
time_delta = check_out_time - check_in_time check_in_time = user_stats[user_id]["check_in_time"]
user_stats[user_id]["check_ins"] += 1 time_delta = check_out_time - check_in_time
user_stats[user_id]["total_time"] += time_delta user_stats[user_id]["check_ins"] += 1
user_stats[user_id]["check_in_time"] = None user_stats[user_id]["total_time"] += time_delta
user_stats[user_id]["check_in_time"] = None
# Save user stats to file
with open("user_stats.json", "w") as f: # Save user stats to file
json.dump(user_stats, f) with open("user_stats.json", "w") as f:
await message.channel.send(f"{message.author.mention} You have been checked out. Your session was {time_delta:.2f} seconds.") json.dump(user_stats, f)
await message.channel.send(f"{message.author.mention} You have been checked out. Your session was {time_delta:.2f} seconds.")
elif message.content.lower() == "stats":
stats_embed = discord.Embed(title="User stats :trophy:", color=0x000000) elif message.content.lower() == "stats":
sorted_user_stats = sorted(user_stats.items(), key=lambda x: x[1]["total_time"], reverse=True) stats_embed = discord.Embed(title="User stats :trophy:", color=0x000000)
table_rows = [["Name", "Check-ins", "Total Time"]] sorted_user_stats = sorted(user_stats.items(), key=lambda x: x[1]["total_time"], reverse=True)
for user_id, stats in sorted_user_stats: table_rows = [["Name", "Check-ins", "Total Time"]]
if stats["check_in_time"] is None: for user_id, stats in sorted_user_stats:
total_time_seconds = stats["total_time"] if stats["check_in_time"] is None:
hours, total_time_seconds = divmod(total_time_seconds, 3600) total_time_seconds = stats["total_time"]
minutes, total_time_seconds = divmod(total_time_seconds, 60) hours, total_time_seconds = divmod(total_time_seconds, 3600)
seconds, fractions = divmod(total_time_seconds, 1) minutes, total_time_seconds = divmod(total_time_seconds, 60)
fractions_str = f"{fractions:.3f}"[2:] seconds, fractions = divmod(total_time_seconds, 1)
username = client.get_user(int(user_id)).name fractions_str = f"{fractions:.3f}"[2:]
table_rows.append([username, str(stats["check_ins"]), f"{int(hours)}h {int(minutes)}m {int(seconds)}s {fractions_str}ms"]) username = client.get_user(int(user_id)).name
else: table_rows.append([username, str(stats["check_ins"]), f"{int(hours)}h {int(minutes)}m {int(seconds)}s {fractions_str}ms"])
username = client.get_user(int(user_id)).name else:
table_rows.append([username, "Currently checked in", "-"]) username = client.get_user(int(user_id)).name
table_columns = list(zip(*table_rows[1:])) table_rows.append([username, "Currently checked in", "-"])
table_fields = table_rows[0] table_columns = list(zip(*table_rows[1:]))
for field, values in zip(table_fields, table_columns): table_fields = table_rows[0]
stats_embed.add_field(name=field, value="\n".join(values), inline=True) for field, values in zip(table_fields, table_columns):
await message.channel.send(embed=stats_embed) stats_embed.add_field(name=field, value="\n".join(values), inline=True)
await message.channel.send(embed=stats_embed)
# GarfGifs
@client.event # GarfGifs
async def send_gif(message, search_term): @client.event
lmt = 50 async def send_gif(message, search_term):
ckey = "garfbot" lmt = 50
r = requests.get(f"https://tenor.googleapis.com/v2/search?q={search_term}&key={gapikey}&client_key={ckey}&limit={lmt}") ckey = "garfbot"
if r.status_code == 200: r = requests.get(f"https://tenor.googleapis.com/v2/search?q={search_term}&key={gapikey}&client_key={ckey}&limit={lmt}")
top_50gifs = json.loads(r.content) if r.status_code == 200:
gif_url = random.choice(top_50gifs["results"])["itemurl"] top_50gifs = json.loads(r.content)
print(gif_url) gif_url = random.choice(top_50gifs["results"])["itemurl"]
try: print(gif_url)
await message.channel.send(gif_url) try:
except KeyError: await message.channel.send(gif_url)
await message.channel.send("Oops, something went wrong.") except KeyError:
else: await message.channel.send("Oops, something went wrong.")
await message.channel.send(f"`Oops, something went wrong. Error code: {r.status_code}`") else:
await message.channel.send(f"`Oops, something went wrong. Error code: {r.status_code}`")
# Run GarfBot
try: # Run GarfBot
client.run(garfkey) try:
except Exception as e: client.run(garfkey)
e = str(e) except Exception as e:
print(f"GarfBot Error: {e}") e = str(e)
print(f"GarfBot Error: {e}")

View File

@ -4,16 +4,16 @@ import discord
import os import os
openai.api_key = config.OPENAI_TOKEN openai.api_key = config.OPENAI_TOKEN
jonkey = config.JONBOT_TOKEN
intents = discord.Intents.default() intents = discord.Intents.default()
intents.messages = True intents.messages = True
intents.message_content = True intents.message_content = True
client = discord.Client(intents=intents) client = discord.Client(intents=intents)
jonkey = config.JONBOT_TOKEN
@client.event @client.event
async def on_ready(): async def on_ready():
print(f"Logged in as {client.user.name} running gpt-3.5-turbo-0613.") print(f"Logged in as {client.user.name} running gpt-3.5-turbo-0613.", flush=True)
@client.event @client.event
async def on_message(message): async def on_message(message):

View File

@ -13,13 +13,12 @@ client = discord.Client(intents=intents)
@client.event @client.event
async def on_ready(): async def on_ready():
print(f"Logged in as {client.user.name} running gpt-3.5-turbo-0613.") print(f"Logged in as {client.user.name} running gpt-3.5-turbo-0613.", flush=True)
@client.event @client.event
async def on_message(message): async def on_message(message):
if message.author == client.user: if message.author == client.user:
return return
if message.content.lower().startswith("hey money") or isinstance(message.channel, discord.DMChannel): if message.content.lower().startswith("hey money") or isinstance(message.channel, discord.DMChannel):
question = message.content[9:] if message.content.lower().startswith("hey money") else message.content question = message.content[9:] if message.content.lower().startswith("hey money") else message.content
try: try: