Araeynn commited on
Commit
29b574d
1 Parent(s): fc66d86

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +108 -134
app.py CHANGED
@@ -1,142 +1,116 @@
1
- from discord import app_commands
2
- import requests
3
- import discord
4
- import asyncio
5
- from discord.ext.commands import is_owner, Context, has_permissions
6
- import os
7
  from typing import Optional
8
 
9
- intents = discord.Intents.all()
10
- client = discord.Client(intents=intents)
11
- tree = app_commands.CommandTree(client)
12
-
13
- url = "https://huggingface.co/chat/conversation"
14
-
15
- # load system prompt
16
- try:
17
- with open("sysp.txt", "r") as f:
18
- sysp = f.read()
19
- except:
20
- sysp = ""
21
-
22
- # models
23
- mixtral = "mistralai/Mixtral-8x7B-Instruct-v0.1"
24
- llama = "meta-llama/Llama-2-70b-chat-hf"
25
- openchat = "openchat/openchat-3.5-0106"
26
- mistral = "mistralai/Mistral-7B-Instruct-v0.2"
27
- hermes = "NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO"
28
- codellama = "codellama/CodeLlama-70b-Instruct-hf"
29
-
30
- async def chat(conversationId, ip, cookie):
31
- s = requests.Session()
32
- url = f"https://huggingface.co/chat/conversation/{conversationId}"
33
-
34
- payload = {
35
- "inputs": ip,
36
- "id": cookie,
37
- "is_retry": False,
38
- "is_continue": False,
39
- "web_search": False,
40
- "files": []
41
- }
42
-
43
- headers = {
44
- "authority": "huggingface.co",
45
- "accept": "*/*",
46
- "accept-language": "en-US,en;q=0.9",
47
- "content-type": "application/json",
48
- }
49
-
50
- response = s.post(url, json=payload, headers=headers)
51
- return response
52
- s.close()
53
-
54
- @client.tree.command(
55
- description="Starts the conversation with Lyre.",
56
- guild=discord.Object(id=1079318749116641320)
57
- )
58
- @app_commands.describe(
59
- channel='The channel to start the conversation in. Defaults to the channel it was called in.',
60
- )
61
- @has_permissions(manage_channels=True, manage_messages=True)
62
- async def start(ctx: discord.Interaction, channel: Optional[discord.AppCommandOptionType.channel]=None):
63
- s = requests.Session()
64
- payload = {
65
- "model": mixtral,
66
- "preprompt": sysp
67
- }
68
- headers = {
69
- "authority": "huggingface.co",
70
- "accept": "*/*",
71
- "accept-language": "en-US,en;q=0.9",
72
- "content-type": "application/json"
73
- }
74
- if channel == None:
75
- chping = f"<#{ctx.channel_id}>"
76
- with open(str(ctx.channel_id), "w") as f:
77
- f.write(s.cookies.get("hf-chat") + "\n" + response.json.loads(response.text)['conversationId'])
78
- else:
79
- chping = f"<#{channel.id}>"
80
- with open(str(ctx.channel_id), "w") as f:
81
- f.write(s.cookies.get("hf-chat") + "\n" + response.json.loads(response.text)['conversationId'])
82
- ctx.response.send_message(f"Started a conversation in {chping}")
83
-
84
- @start.error
85
- async def start_error(error, ctx):
86
- if isinstance(error, commands.MissingPermissions):
87
- ctx.response.send_message(f"Missing permissions in {chping}")
88
-
89
- @client.tree.command(
90
- description="Ends the conversation with Lyre.",
91
- guild=discord.Object(id=1079318749116641320)
92
- )
93
- @app_commands.describe(
94
- channel='The channel to end the conversation in. Defaults to the channel it was called in.',
95
- )
96
- @has_permissions(manage_channels=True, manage_messages=True)
97
- async def start(ctx: discord.Interaction, channel: Optional[discord.AppCommandOptionType.channel]=None):
98
- s = requests.Session()
99
- payload = {
100
- "model": mixtral,
101
- "preprompt": sysp
102
- }
103
- headers = {
104
- "authority": "huggingface.co",
105
- "accept": "*/*",
106
- "accept-language": "en-US,en;q=0.9",
107
- "content-type": "application/json"
108
- }
109
- if channel == None:
110
- chping = f"<#{ctx.channel_id}>"
111
- os.remove(str(ctx.channel_id))
112
- else:
113
- chping = f"<#{channel.id}>"
114
- os.remove(str(ctx.channel_id))
115
- ctx.response.send_message(f"Ended the conversation in {chping}")
116
- s.close()
117
-
118
- @end.error
119
- async def end_error(error, ctx):
120
- if isinstance(error, commands.MissingPermissions):
121
- ctx.response.send_message(f"Missing permissions in {chping}")
122
-
123
- @client.command()
124
- @is_owner()
125
- async def sync(ctx: Context) -> None:
126
- synced = await client.tree.sync()
127
- await ctx.reply("{} commands synced".format(len(synced)))
128
 
129
  @client.event
130
  async def on_ready():
131
- print("Ready!")
132
- synced = await client.tree.sync()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
 
134
- @client.event
135
- async def on_message_create(msg):
136
- if os.path.exists(str(msg.channel.id)) or isinstance(msg.channel, discord.DMChannel):
137
- with open(str(msg.channel.id), "r") as f:
138
- cookie, id = f.read().split("\n")
139
- r = await chat(id, "{" + str(msg.author) + "}\n" + msg.content, id)
140
- await msg.reply(json.loads("{" + r.text.split("finalAnswer")[-1][2:].strip())["text"].strip())
141
 
142
  client.run(os.environ["TOKEN"])
 
 
 
 
 
 
 
1
  from typing import Optional
2
 
3
+ import discord
4
+ from discord import app_commands
5
+
6
+
7
+ MY_GUILD = discord.Object(id=0) # replace with your guild id
8
+
9
+
10
+ class MyClient(discord.Client):
11
+ def __init__(self, *, intents: discord.Intents):
12
+ super().__init__(intents=intents)
13
+ # A CommandTree is a special type that holds all the application command
14
+ # state required to make it work. This is a separate class because it
15
+ # allows all the extra state to be opt-in.
16
+ # Whenever you want to work with application commands, your tree is used
17
+ # to store and work with them.
18
+ # Note: When using commands.Bot instead of discord.Client, the bot will
19
+ # maintain its own tree instead.
20
+ self.tree = app_commands.CommandTree(self)
21
+
22
+ # In this basic example, we just synchronize the app commands to one guild.
23
+ # Instead of specifying a guild to every command, we copy over our global commands instead.
24
+ # By doing so, we don't have to wait up to an hour until they are shown to the end-user.
25
+ async def setup_hook(self):
26
+ # This copies the global commands over to your guild.
27
+ self.tree.copy_global_to(guild=MY_GUILD)
28
+ await self.tree.sync(guild=MY_GUILD)
29
+
30
+
31
+ intents = discord.Intents.default()
32
+ client = MyClient(intents=intents)
33
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
  @client.event
36
  async def on_ready():
37
+ print(f'Logged in as {client.user} (ID: {client.user.id})')
38
+ print('------')
39
+
40
+
41
+ @client.tree.command()
42
+ async def hello(interaction: discord.Interaction):
43
+ """Says hello!"""
44
+ await interaction.response.send_message(f'Hi, {interaction.user.mention}')
45
+
46
+
47
+ @client.tree.command()
48
+ @app_commands.describe(
49
+ first_value='The first value you want to add something to',
50
+ second_value='The value you want to add to the first value',
51
+ )
52
+ async def add(interaction: discord.Interaction, first_value: int, second_value: int):
53
+ """Adds two numbers together."""
54
+ await interaction.response.send_message(f'{first_value} + {second_value} = {first_value + second_value}')
55
+
56
+
57
+ # The rename decorator allows us to change the display of the parameter on Discord.
58
+ # In this example, even though we use `text_to_send` in the code, the client will use `text` instead.
59
+ # Note that other decorators will still refer to it as `text_to_send` in the code.
60
+ @client.tree.command()
61
+ @app_commands.rename(text_to_send='text')
62
+ @app_commands.describe(text_to_send='Text to send in the current channel')
63
+ async def send(interaction: discord.Interaction, text_to_send: str):
64
+ """Sends the text into the current channel."""
65
+ await interaction.response.send_message(text_to_send)
66
+
67
+
68
+ # To make an argument optional, you can either give it a supported default argument
69
+ # or you can mark it as Optional from the typing standard library. This example does both.
70
+ @client.tree.command()
71
+ @app_commands.describe(member='The member you want to get the joined date from; defaults to the user who uses the command')
72
+ async def joined(interaction: discord.Interaction, member: Optional[discord.Member] = None):
73
+ """Says when a member joined."""
74
+ # If no member is explicitly provided then we use the command user here
75
+ member = member or interaction.user
76
+
77
+ # The format_dt function formats the date time into a human readable representation in the official client
78
+ await interaction.response.send_message(f'{member} joined {discord.utils.format_dt(member.joined_at)}')
79
+
80
+
81
+ # A Context Menu command is an app command that can be run on a member or on a message by
82
+ # accessing a menu within the client, usually via right clicking.
83
+ # It always takes an interaction as its first parameter and a Member or Message as its second parameter.
84
+
85
+ # This context menu command only works on members
86
+ @client.tree.context_menu(name='Show Join Date')
87
+ async def show_join_date(interaction: discord.Interaction, member: discord.Member):
88
+ # The format_dt function formats the date time into a human readable representation in the official client
89
+ await interaction.response.send_message(f'{member} joined at {discord.utils.format_dt(member.joined_at)}')
90
+
91
+
92
+ # This context menu command only works on messages
93
+ @client.tree.context_menu(name='Report to Moderators')
94
+ async def report_message(interaction: discord.Interaction, message: discord.Message):
95
+ # We're sending this response message with ephemeral=True, so only the command executor can see it
96
+ await interaction.response.send_message(
97
+ f'Thanks for reporting this message by {message.author.mention} to our moderators.', ephemeral=True
98
+ )
99
+
100
+ # Handle report by sending it into a log channel
101
+ log_channel = interaction.guild.get_channel(0) # replace with your channel id
102
+
103
+ embed = discord.Embed(title='Reported Message')
104
+ if message.content:
105
+ embed.description = message.content
106
+
107
+ embed.set_author(name=message.author.display_name, icon_url=message.author.display_avatar.url)
108
+ embed.timestamp = message.created_at
109
+
110
+ url_view = discord.ui.View()
111
+ url_view.add_item(discord.ui.Button(label='Go to Message', style=discord.ButtonStyle.url, url=message.jump_url))
112
+
113
+ await log_channel.send(embed=embed, view=url_view)
114
 
 
 
 
 
 
 
 
115
 
116
  client.run(os.environ["TOKEN"])