Skip to content

Commit 1547abe

Browse files
authored
Update bot.py
1 parent e7f1aab commit 1547abe

File tree

1 file changed

+236
-78
lines changed

1 file changed

+236
-78
lines changed

bot.py

+236-78
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import discord, aiohttp, asyncio, datetime
2-
from discord import app_commands
1+
import discord, aiohttp, asyncio, datetime, re
2+
from discord import ui, app_commands
33
from discord.ext import commands
44
from discord.ext.commands import bot
55

@@ -8,7 +8,131 @@
88
#chunk_guilds_at_startup is for not saving guilds datas in the cache (less ram consumption)
99
#case_insensitive is for using command with full caps for exemple
1010

11-
tree = client.tree #for slash commands
11+
tree = client.tree
12+
13+
start_time = datetime.datetime.now(datetime.timezone.utc)
14+
15+
async def generate_image(prompt, model, timeout=120):
16+
counter = 0
17+
api_url = "https://api.sitius.ir/"
18+
data = {
19+
"model": model,
20+
"prompt": prompt,
21+
"steps": 30,
22+
"cfg_scale": 7,
23+
"sampler" : "Euler",
24+
"negative_prompt": "canvas frame, cartoon, 3d, ((disfigured)), ((bad art)), ((deformed)), ((extra limbs)), ((close up)), ((b&w)), weird colors, blurry, (((duplicate))), ((morbid)), ((mutilated)), [out of frame], extra fingers, mutated hands, ((poorly drawn hands)), ((poorly drawn face)), (((mutation))), ((ugly)), (((bad proportions))), (malformed limbs), ((missing arms)), ((missing legs)), (((extra arms))), (((extra legs))), (fused fingers), (too many fingers), (((long neck))), Photoshop, video game, tiling, poorly drawn feet, body out of frame, nsfw"
25+
}
26+
headers = {"auth": "test"}
27+
28+
async with aiohttp.ClientSession() as session:
29+
async with session.post(f"{api_url}v1/generate/", json=data, headers=headers) as response:
30+
job_id = await response.json()
31+
while counter < timeout :
32+
async with session.get(api_url + f"v1/image/{job_id}/") as r:
33+
if r.status == 200:
34+
url = await r.json()
35+
return url
36+
await asyncio.sleep(0.5)
37+
counter += 0.5
38+
39+
40+
41+
42+
43+
44+
45+
46+
generating_embed = discord.Embed(
47+
title="Generating Image",
48+
description="Image Is Generating, It takes 30 ~ 50 seconds to generate",
49+
color=discord.Color.orange()
50+
)
51+
52+
53+
54+
55+
56+
class RetryButton(ui.View):
57+
def __init__(self, prompt, model, user, p1) -> None:
58+
super().__init__()
59+
self.prompt = prompt
60+
self.model = model
61+
self.user = user
62+
self.p1 = p1
63+
64+
65+
@discord.ui.button(label='retry', emoji="♻️", style=discord.ButtonStyle.green, custom_id='retry')
66+
async def retry(self, interaction: discord.Interaction, button: ui.Button):
67+
button.disabled = True
68+
await interaction.message.edit(view=self)
69+
await interaction.response.edit_message(content=None, embed=generating_embed)
70+
71+
image = await generate_image(self.prompt, self.model)
72+
73+
74+
if image:
75+
print(f"Prompt: {self.prompt}\nImage URL: {image}")
76+
image_embed = discord.Embed(title="Generated Image", color=discord.Color.blue())
77+
image_embed.set_image(url=image)
78+
image_embed.add_field(name="Prompt", value=self.prompt, inline=False)
79+
image_embed.add_field(name="Model", value=self.model, inline=False)
80+
button.disabled = False
81+
await interaction.message.edit(view=self)
82+
await interaction.edit_original_response(content=None, embed=image_embed)
83+
84+
85+
86+
else:
87+
await interaction.response.edit_message(content="Failed to upload image.", embed=None)
88+
89+
async def interaction_check(self, interaction):
90+
if interaction.user.id != self.p1:
91+
await interaction.response.send_message(f"You do not own this command {interaction.user.mention}", ephemeral= True)
92+
return interaction.user.id == self.p1
93+
94+
95+
96+
97+
async def check_words(prompt: str) -> bool:
98+
banned_patterns = [
99+
r"\bloli\b",
100+
r"\bbaby\b",
101+
r"\bshota\b",
102+
r"\bunderage\b",
103+
r"\bkid\b",
104+
r"\bchild\b",
105+
r"\blittle girl\b",
106+
r"\byoung girl\b",
107+
r"\bpetite\b",
108+
r"\blittle boy\b",
109+
r"\byoung boy\b",
110+
r"\bteen\b",
111+
r"\btween\b",
112+
r"\bminor\b",
113+
r"\badolescent\b",
114+
r"\bpreteen\b",
115+
r"\bsmall girl\b",
116+
r"\bsmall boy\b",
117+
# Match age patterns only if the age is below 18
118+
r"\b(1[0-7]|[1-9])\s?yo\b", # e.g., 2yo, 15yo (but not 18yo or older)
119+
r"\b(1[0-7]|[1-9])\s?years?\s?old\b", # e.g., 3 years old, 10 yrs old (but not 18 or older)
120+
r"\b(1[0-7]|[1-9])\s?-year-old\b", # e.g., 4-year-old, 7-year-old (but not 18 or older)
121+
]
122+
123+
prompt_lower = prompt.lower()
124+
for pattern in banned_patterns:
125+
if re.search(pattern, prompt_lower):
126+
return True
127+
return False
128+
129+
130+
131+
132+
133+
134+
135+
12136

13137
@client.event
14138
async def on_ready():
@@ -21,119 +145,153 @@ async def update_stats():
21145
total_members = sum(guild.member_count for guild in client.guilds)
22146
activity_text = f"In {len(client.guilds)} servers | Serving {total_members} members"
23147
await client.change_presence(activity=discord.Game(name=activity_text))
24-
await asyncio.sleep(360)
148+
await asyncio.sleep(1800)
149+
150+
@client.event
151+
async def on_message(message):
152+
if message.author == client.user:
153+
return
154+
155+
if message.channel.type == discord.ChannelType.private:
156+
title = 'The Bot Can Only Be Used In Servers'
157+
else:
158+
title='Bot Is Now Based On / Commands Only'
25159

160+
response_embed = discord.Embed(title=title,
161+
description=f"[Invite](https://discord.com/oauth2/authorize?client_id=1180105597874610206&permissions=277025515584&scope=bot) the bot for your server!\n[Support](https://discord.com/invite/bVUa2En9) our community server!",
162+
color=discord.Color.blue())
163+
164+
if message.content == client.user.mention:
165+
await message.channel.send(embed=response_embed)
26166

27-
#generating embed
28-
generating_embed = discord.Embed(
29-
title="Generating Image",
30-
description="Image Is Generating, It takes 30 ~ 50 seconds to generate",
31-
color=discord.Color.orange())
167+
await client.process_commands(message)
32168

169+
170+
@tree.command(name = "stats", description = "Get bot statistics")
171+
async def stats(interaction: discord.Interaction):
172+
total_servers = len(client.guilds)
173+
total_members = sum(guild.member_count for guild in client.guilds)
174+
uptime = datetime.datetime.now(datetime.timezone.utc) - start_time
175+
total_seconds, microseconds = divmod(uptime.microseconds + (uptime.seconds + uptime.days * 86400) * 10 ** 6, 10 ** 6)
176+
days = int(total_seconds // 86400)
177+
uptime_string = f"{days} days, {int((total_seconds % 86400) // 3600)} hours, {int((total_seconds % 3600) // 60)} minutes, {int(total_seconds % 60)} seconds, and {int(microseconds)} microseconds"
178+
embed = discord.Embed(
179+
title = "Bot Statistics",
180+
description = f"Here are the current statistics of the bot:\n\nTotal Servers: {total_servers}\nTotal Members: {total_members}\nUptime: {uptime_string}",
181+
color = discord.Color.blue()
182+
)
183+
await interaction.response.send_message(embed=embed)
184+
185+
186+
@client.command(name="machine", description="Get bot's machine statistics")
187+
async def machine(ctx):
188+
try:
189+
ram = psutil.virtual_memory()
190+
cpu = psutil.cpu_percent()
191+
disk = psutil.disk_usage('/')
33192

34-
#define the api header
35-
async def head(prompt, image_format, model):
36-
width , height = map(int, image_format.split("x"))
37-
api_key = ""#change by your api key on the bot from visioncraft : https://t.me/VisionCraft_bot (use the command /key)
38-
data = {
39-
"model": model,
40-
"prompt": prompt,
41-
"token": api_key,
42-
"width": width,
43-
"height": height
44-
}
45-
return data
193+
performance_rate = int((ram.percent + cpu + disk.percent) / 3)
46194

47-
#make the request to the api
48-
async def generate_image(data) -> bytes:
49-
api_url = "https://visioncraft.top"
50-
async with aiohttp.ClientSession() as session:
51-
async with session.post(f"{api_url}/sd", json=data) as response:
52-
image = await response.read()
53-
return image
195+
embed = discord.Embed(title="Machine Stats", color=discord.Color.blue())
196+
embed.add_field(name="Free RAM", value=f"{ram.available / (1024 ** 3):.2f} GB / {ram.total / (1024 ** 3):.2f} GB", inline=True)
197+
embed.add_field(name="Free CPU", value=f"{100 - cpu:.2f}%", inline=True)
198+
embed.add_field(name="Free Disk Space", value=f"{disk.free / (1024 ** 3):.2f} GB / {disk.total / (1024 ** 3):.2f} GB", inline=True)
199+
embed.add_field(name="Performance Rate", value=f"{performance_rate}% out of 100%", inline=False)
54200

55-
#upload the image on a file host
56-
async def telegraph_file_upload(file_bytes):
57-
url = 'https://telegra.ph/upload'
58-
try:
59-
data = aiohttp.FormData()
60-
data.add_field('file', file_bytes, filename='image.png', content_type='image/png')
61-
62-
async with aiohttp.ClientSession() as session:
63-
async with session.post(url, data=data) as response:
64-
response_data = await response.json()
65-
if response.status == 200 and response_data and isinstance(response_data, list) and 'src' in response_data[0]:
66-
telegraph_url = response_data[0]['src']
67-
full_url = f'https://telegra.ph{telegraph_url}'
68-
return full_url
69-
else:
70-
print(f'Unexpected response data or status: {response_data}, Status: {response.status}')
71-
return None
201+
await ctx.send(embed=embed)
72202
except Exception as e:
73-
print(f'Error uploading file to Telegraph: {str(e)}')
74-
return None
203+
await ctx.send(f"An error occurred: {e}")
204+
205+
@client.event
206+
async def on_guild_join(guild):
207+
# Details about the server
208+
owner = guild.owner
209+
server_name = guild.name
210+
if owner: # Ensure there is an owner object
211+
owner_name = f"{owner.name}#{owner.discriminator}" # The owner's username and discriminator
212+
owner_id = owner.id # The owner's ID
213+
214+
# Construct the message
215+
message_content = f"{owner_name} (ID: {owner_id}) added the bot to their server {server_name}."
216+
217+
# Fetch your user object by your Discord user ID
218+
user = await client.fetch_user(761886210120744990) # Your Discord ID
219+
220+
# Send the message
221+
if user:
222+
await user.send(message_content)
223+
else:
224+
print("Failed to fetch user for DM.")
225+
else:
226+
print("Failed to retrieve owner information.")
227+
228+
229+
75230

76-
#simple command
77231
@client.command()
78232
async def imagine(ctx, *, prompt: str):
79233
message = await ctx.send(embed=generating_embed)
234+
if await check_words(prompt):
235+
return await message.edit(content="your prompt contain banned word", embed=None)
236+
image = await generate_image(prompt, model="Realistic_Vision_v5.0")
80237

81-
data = await head(prompt, image_format="1024x1024", model="RealVisXLV40Turbo-40")
82-
image = await generate_image(data)
83-
telegraph_url = await telegraph_file_upload(image)
84238

85-
if telegraph_url:
239+
if image:
240+
view=RetryButton(prompt, model, ctx.user.name, ctx.user.id)
241+
86242
image_embed = discord.Embed(title="Generated Image", color=discord.Color.blue())
87-
image_embed.set_image(url=telegraph_url)
243+
image_embed.set_image(url=image)
244+
image_embed.add_field(name="Prompt", value=prompt, inline=False)
245+
image_embed.add_field(name="Model", value="Realistic_Vision_v5.0", inline=False)
88246

89-
await message.edit(content=None, embed=image_embed)
90-
print(f"Image URL: {telegraph_url}") # Log the image URL to the console
247+
await message.edit(content=None, embed=image_embed, view = view)
248+
print(f"Image URL: {image}") # Log the image URL to the console
91249
else:
92250
await message.edit(content="Failed to upload image.", embed=None)
93251

94252

95253

96-
#slash command
254+
#how to use
97255
@tree.command(description="generate images by ai")
98-
@app_commands.describe(prompt="description of the image", private="make the image visble for you or everyone", image_format="the format of the image", image_type="type of the image like anime, 3d, etc...")
256+
@app_commands.describe(prompt="description of the image", private="make the image visble for you or everyone", image_type="type of the image like anime, 3d, etc...")
99257
@app_commands.choices(
100-
image_format = [
101-
app_commands.Choice(name="default・Square", value="1024x1024"),
102-
app_commands.Choice(name="Portrait", value="768x1024"),
103-
app_commands.Choice(name="Landscape", value="1024x768"),
104-
],
105258
private = [
106259
app_commands.Choice(name="True", value="True"),
107260
app_commands.Choice(name="False", value="False"),
108261
],
109262
image_type = [
110-
app_commands.Choice(name="default・realistic", value="RealVisXLV40Turbo-40"),
111-
app_commands.Choice(name="3D", value="UnrealXL-v1"),
112-
app_commands.Choice(name="anime", value="AnimefromHaDeS-v16HQ"),
113-
]
263+
app_commands.Choice(name="default・realistic", value="Realistic_Vision_v5.0"),
264+
app_commands.Choice(name="3D", value="lyriel_v1.6"),
265+
app_commands.Choice(name="anime", value="anything_V5"),
266+
267+
]
268+
114269
)
115-
async def imagine(ctx : discord.Interaction, prompt: str, image_format: app_commands.Choice[str] = None, image_type: app_commands.Choice[str] = None, private: app_commands.Choice[str] = None):
270+
async def imagine(ctx : discord.Interaction, prompt: str, image_type: app_commands.Choice[str] = None, private: app_commands.Choice[str] = None):
116271
private_value = True if private is not None and private.value == "True" else False
117-
img_format = image_format.value if image_format is not None else "1024x1024"
118-
model = image_type.value if image_type is not None else "RealVisXLV40Turbo-40"
272+
model = image_type.value if image_type is not None else "Realistic_Vision_v5.0"
119273

120274
await ctx.response.send_message(embed=generating_embed, ephemeral=bool(private_value))
121-
275+
if await check_words(prompt):
276+
return await ctx.edit_original_response(content="your prompt contain banned word", embed=None)
122277

123-
data = await head(prompt, img_format, model)
124-
image = await generate_image(data)
125-
telegraph_url = await telegraph_file_upload(image)
278+
279+
image = await generate_image(prompt, model)
280+
126281

127-
if telegraph_url:
282+
if image:
283+
view=RetryButton(prompt, model, ctx.user.name, ctx.user.id)
284+
print(f"Prompt: {prompt}\nImage URL: {image}")
128285
image_embed = discord.Embed(title="Generated Image", color=discord.Color.blue())
129-
image_embed.set_image(url=telegraph_url)
130-
print(f"Image URL: {telegraph_url}")
131-
await ctx.edit_original_response(content=None, embed=image_embed)
286+
image_embed.set_image(url=image)
287+
image_embed.add_field(name="Prompt", value=prompt, inline=False)
288+
image_embed.add_field(name="Model", value=model, inline=False)
289+
await ctx.edit_original_response(content=None, embed=image_embed, view=view)
132290

133291

134292
else:
293+
135294
await ctx.edit_original_response(content="Failed to upload image.", embed=None)
136295

137-
138296

139297
client.run("")#use your bot token

0 commit comments

Comments
 (0)