1
1
from __future__ import annotations
2
2
3
- from typing import TYPE_CHECKING , Optional
3
+ from typing import TYPE_CHECKING , Optional , Union
4
4
5
+ import asyncpg .exceptions
5
6
import discord
6
7
from discord .ext import commands
7
8
9
+ from libs .snippets .model import create_snippet , get_snippet
10
+ from libs .snippets .views import SnippetPreCreationConfirmationView
11
+
8
12
if TYPE_CHECKING :
9
13
from libs .utils .context import GuildContext
10
14
from rodhaj import Rodhaj
@@ -64,8 +68,41 @@ async def remove(self, ctx: GuildContext, name: str):
64
68
# TODO: Run all str inputs through custom converters
65
69
@commands .guild_only ()
66
70
@snippet .command ()
67
- async def new (self , ctx , name : str , * , content : Optional [str ] = None ):
68
- await ctx .send ("placeholder for snippet new" )
71
+ async def new (
72
+ self ,
73
+ ctx : GuildContext ,
74
+ name : str ,
75
+ * ,
76
+ content : Optional [str ] = None ,
77
+ ):
78
+ if (
79
+ await get_snippet (self .pool , ctx .guild .id , ctx .message .author .id , name )
80
+ is not None
81
+ ):
82
+ await ctx .send (
83
+ content = f"Snippet `{ name } ` already exists!" ,
84
+ )
85
+ return
86
+
87
+ if not content :
88
+ timeout = 15
89
+ confirmation_view = SnippetPreCreationConfirmationView (
90
+ self .bot , ctx , name , timeout
91
+ )
92
+ await ctx .reply (
93
+ content = f"Create snippet with id `{ name } `?" ,
94
+ view = confirmation_view ,
95
+ delete_after = timeout ,
96
+ )
97
+ else :
98
+ self .bot .dispatch (
99
+ "snippet_create" ,
100
+ ctx .guild ,
101
+ ctx .message .author ,
102
+ name ,
103
+ content ,
104
+ ctx ,
105
+ )
69
106
70
107
@commands .guild_only ()
71
108
@snippet .command (name = "list" )
@@ -111,7 +148,6 @@ async def edit(self, ctx: GuildContext, name: str, content: Optional[str]):
111
148
WHERE name = $1
112
149
RETURNING name
113
150
"""
114
-
115
151
result = await self .pool .fetchrow (query , name , content )
116
152
if result is None :
117
153
await ctx .reply (
@@ -135,6 +171,27 @@ async def edit(self, ctx: GuildContext, name: str, content: Optional[str]):
135
171
ephemeral = True ,
136
172
)
137
173
174
+ @commands .Cog .listener ()
175
+ async def on_snippet_create (
176
+ self ,
177
+ guild : discord .Guild ,
178
+ creator : Union [discord .User , discord .Member ],
179
+ snippet_name : str ,
180
+ snippet_text : str ,
181
+ response_context : GuildContext ,
182
+ ):
183
+ try :
184
+ await create_snippet (
185
+ self .pool , guild .id , creator .id , snippet_name , snippet_text
186
+ )
187
+ if response_context :
188
+ await response_context .send (
189
+ "Snippet created successfully" , delete_after = 5
190
+ )
191
+ except asyncpg .exceptions .UniqueViolationError :
192
+ if response_context :
193
+ await response_context .send ("Snippet already exists" , delete_after = 5 )
194
+
138
195
139
196
async def setup (bot : Rodhaj ):
140
197
await bot .add_cog (Snippets (bot ))
0 commit comments