GammaRPBot/main-bot.py

151 lines
5.9 KiB
Python
Raw Normal View History

import discord
import aiosqlite
from discord.ext import commands
from discord import app_commands
import logging
import sys
from public_env import *
from GammaRPBot_Define import GammaRPBot
2024-12-15 16:21:01 +01:00
import base64
2024-12-16 23:00:10 +01:00
import aiohttp
formatter = discord.utils._ColourFormatter()
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter)
logging.basicConfig(level=logging.INFO, handlers=[handler])
logger = logging.getLogger()
2024-12-16 23:00:10 +01:00
_sql_table="""CREATE TABLE personnages (
nom_court varchar(255),
nom_complet text,
image text,
histoire text,
pouvoirs text,
uuid TEXT,
age INTEGER,
sexe TEXT,
money INTEGER DEFAULT 50,
guild_id INTEGER NULL
)"""
intents = discord.Intents.all()
bot = GammaRPBot(intents)
@bot.event
async def on_ready():
bot.db = await aiosqlite.connect("main.db")
2024-12-15 16:03:54 +01:00
bot.db.row_factory = aiosqlite.Row
await bot.load_extension("perso_commands")
await bot.tree.sync()
print(f"Logged in as {bot.user}")
@bot.event
async def on_message(message:discord.Message):
if message.author.bot:
return
if message.content.startswith("g!"):
2024-12-15 16:03:54 +01:00
if len(message.content.split(" "))<2:
return
short_name = message.content.split(" ")[0][2:]
uuid = message.author.id
guild_id = message.guild.id
message_str = message.content[message.content.index(" ")+1:]
if await say_message(uuid,guild_id,short_name,message_str,message.channel):
await message.delete()
@bot.tree.command(name="s",description="Envoyer un message en tant que personnage")
2024-12-15 17:06:01 +01:00
@app_commands.user_install()
@app_commands.describe(id="Le nom court du personnage",message="Le message à envoyer")
@app_commands.allowed_contexts(guilds=True,dms=True,private_channels=True)
2024-12-15 17:06:24 +01:00
@app_commands.allowed_installs(guilds=True,users=True)
async def say(interaction:discord.Interaction,id:str,message:str):
2024-12-15 17:20:10 +01:00
if not await say_message(interaction.user.id,(interaction.guild.id if interaction.guild is not None else -1),id,message,interaction.channel,interaction.response):
print("ok9")
await interaction.response.send_message("Vous n'avez pas ce personnage",ephemeral=True)
return
print("ok10")
await interaction.response.send_message("Message envoyé",ephemeral=True)
2024-12-15 17:20:10 +01:00
async def say_message(userid:int, guildid:int, shortname:str, message:str,channel:discord.TextChannel,interaction_res:discord.InteractionResponse=None):
# print("HELLOWORODL")
# print(userid,guildid,shortname,message,channel)
res = await bot.db.execute("SELECT * FROM personnages WHERE uuid=? AND (guild_id=? OR guild_id IS NULL) AND nom_court=?",(userid,guildid,shortname))
row = await res.fetchone()
await res.close()
if row is None:
return False
# print("ok")
short_name = row["nom_court"]
full_name = row["nom_complet"]
perso_image = row["image"]
# print(short_name,full_name,perso_image)
webhook = None
# print("ok2")
print(channel.guild)
if interaction_res is not None and (channel.guild is None or bot.user.id not in [m.id for m in channel.guild.members] or not channel.permissions_for(channel.guild.me).manage_webhooks):
2024-12-15 17:20:10 +01:00
await interaction_res.send_message(f"**{full_name}({short_name})**: {message}")
return
2024-12-15 15:59:59 +01:00
if discord.utils.get(await channel.webhooks(),name=short_name) is None:
# print("ok3");
webhook = await channel.create_webhook(name=short_name)
# print("ok4")
else:
# print("ok5")
2024-12-15 17:00:50 +01:00
webhook = discord.utils.get(await channel.webhooks(),name=short_name)
# print("ok6")
# print("ok7")
2024-12-15 17:00:50 +01:00
await webhook.send(message,username=full_name,avatar_url=perso_image)
# print("ok8")
return True
2024-12-16 23:00:10 +01:00
# @bot.tree.command(name="ai",description="Envoyer un message par IA en tant que personnage (attention mémoire allant jusqu'a 100 messages max)")
# @app_commands.user_install()
# @app_commands.describe(id="Le nom court du personnage",prompt="La prompt pour le message de l'IA")
# @app_commands.allowed_contexts(guilds=True,dms=True,private_channels=True)
# @app_commands.allowed_installs(guilds=True,users=True)
# async def say_ai(interaction:discord.Interaction,id:str,prompt:str=""):
# if not await say_message(interaction.user.id,(interaction.guild.id if interaction.guild is not None else -1),id,prompt,interaction.channel,interaction.response):
# print("ok9")
# await interaction.response.send_message("Vous n'avez pas ce personnage",ephemeral=True)
# return
# print("ok10")
# await interaction.response.send_message("Message envoyé",ephemeral=True)
# async def say_message_ai(userid:int,guildid:int,shortname:str,channel:discord.TextChannel,interaction_res:discord.InteractionResponse=None, prompt:str=""):
# messages = await channel.history(limit=100).flatten()
# #gemini request using gemini_token
# super_payload = {
# "contents":[
# {
# "role":"user",
# "parts":[{
# "text":"Hello"
# }]
# }
# ]
# }
# res_message=use_gemini(payload=super_payload)
# say_message(userid,guildid,shortname,res_message,channel,interaction_res)
# return True
# async def use_gemini(payload):
# url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key="+gemini_token
# headers={
# "Content-Type":"application/json"
# }
# async with aiohttp.ClientSession().post(url,headers=headers,json=payload) as response:
# result = await response.json()
# print(result)
# try:
# content = result['candidates'][0]['content']['parts'][0]['text']
# return content
# except (KeyError, IndexError) as e:
# # Log the error and response for debugging
# print(f"Error parsing response: {e}")
# print(f"Unexpected response format: {result}")
# return "Error: Unexpected response format"
bot.run(bot_token)