aboutsummaryrefslogtreecommitdiffstats
path: root/cogs/jarvis.py
blob: 2d2a60160b90c1f207f599586450b77f981c1064 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import re
import discord
from discord.ext import commands
import requests
import json
import logging
import shutil

from cogs.compression import Compression
from cogs.downloader import Downloader

logger = logging.getLogger(__name__)


class Jarvis(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_message(self, message):
        print(message.content)
        if message.author == self.bot.user:
            return

        if message.mentions:
            if message.mentions[0].id == self.bot.user.id:
                await self.jarvis(message)

        if "jarvis" in message.content.lower():
            await self.jarvis(message)

    @staticmethod
    async def jarvis(message):
        url = "https://openrouter.ai/api/v1/chat/completions"
        headers = {
            "Authorization": f"Bearer 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",
            "Content-Type": "application/json"
        }
        payload = {
            "model": "mistralai/devstral-2512:free",
            "messages": [
                {
                    "role": "system",
                    "content": "respond in JSON format ONLY.\n"
                               "your task is to tell the program what to do and how to respond after receiving a message.\n"
                               "in the json, only fields need to be filled out, message and action\n"
                               "message is the response that the program will send the user, "
                               "and action is the action the program will do\n"
                               "action can either be: compress or download.\n"
                               "message field has to be filled out in polish.\n"
                               "act like jarvis, be a personal assistant to user, do not use emojis"
                },
                {
                    "role": "user",
                    "content": f"{message.content}"
                }
            ]
        }

        response = requests.post(url, headers=headers, json=payload)
        # Parse the JSON response
        response_data = response.json()
        logger.info(response_data)
        # Extract the content string
        content = response_data['choices'][0]['message']['content']

        # Remove the code block markers and parse the inner JSON
        inner_json_str = content.strip('```json\n').strip('```').strip()
        inner_data = json.loads(inner_json_str)

        # Now you can access the message and action
        response_message = inner_data['message']  # "Proszę podać plik do kompresji lub link do pobrania."
        action = inner_data['action']  # "none OR download OR compress"
        channel = message.channel
        logger.info(response_message)
        logger.debug(action)

        await channel.send(response_message)

        if action == "download":
            # Extract the URL from the message using regex
            url_match = re.search(r'https://(?:[A-Za-z0-9-]+\.)*[A-Za-z0-9-]{1,63}\.[A-Za-z]{2,63}/\S*', message.content).group(0)
            if not url_match:
                await channel.send("Nie znaleziono poprawnego linku w odpowiedzi.")
                return

            response = await Downloader.download_standalone(url=url_match)
            if isinstance(response, dict):
                if response["status"] == "success":
                    if response["type"] == "url":
                        await channel.send(f"pobioron i wysyłon: {response['content']}")
                    elif response["type"] == "file":
                        file_data = response["content"]
                        await channel.send("wysyłon:", file=discord.File(file_data))
                        shutil.rmtree(response["temp_dir"])
                else:
                    logger.error(f"Error: {response['content']}")
                    if 'details' in response:
                        logger.error(f"Details: {response['details']}")
                    shutil.rmtree(response["temp_dir"])

            elif action == "compress":
                pass

def setup(bot):
    bot.add_cog(Jarvis(bot))