-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmain.py
133 lines (98 loc) · 3.41 KB
/
main.py
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#!/usr/bin/env python3
# Telegram bot for Craiyon Image generator
# Github : https://github.com/Kourva/CraiyonBot
# Imports
import requests
import telebot
import base64
import json
import os
# Config
with open("token.env", "r") as config:
Token = config.read().strip().split("=")[1]
# Client
bot = telebot.TeleBot(Token)
# User class: which creates a member with needed stuff.
class User:
def __init__(self, message) -> None:
# takes user info from message
self.fname = message.from_user.first_name
self.lname = message.from_user.last_name
self.uname = message.from_user.username
self.usrid = message.from_user.id
# Craiyon class: which creates images using craiyon
class Craiyon:
def __init__(self, prompt):
self.prompt = prompt
# generates and saves the images
def generate(self):
craiyon = "https://backend.craiyon.com/generate"
payload = {
"prompt": self.prompt,
}
try:
response = requests.post(url=craiyon, json=payload, timeout=160)
result = response.json()["images"]
for index, image in enumerate(result, start=1):
with open(f"generated/{self.prompt}_{index}.webp", "wb") as file:
file.write(base64.decodebytes(image.encode("utf-8")))
except Exception as ex:
return False
## LOCKER
status = False
def lock():
global status
status = True
def unlock():
global status
status = False
# Start command: will be executed when /start pressed.
@bot.message_handler(commands=["start"])
def start_command(message):
# Gets user information
user = User(message)
name = user.fname if user.fname is not None else f"Unknown User"
# Send hello message
bot.reply_to(message, "Hi. Use 'ai your text' to generate images")
# Craiyon image generator
@bot.message_handler(func=lambda message: message.text.startswith("ai"))
def craiyon_generator(message):
if status == False:
lock()
# Gets user information
user = User(message)
name = user.fname if user.fname is not None else f"Unknown User"
# Sends waiting prompt
temp = bot.reply_to(message, "Please wait. It can up to 3 minutes")
# Sets variables
images = []
usrmsg = message.text.split("ai")[1]
# Deletes old images (if any)
path = os.listdir("generated")
if len(path) >= 1:
for item in path:
os.remove(f"generated/{item}")
print("old images deleted")
# Gets images from result
result = Craiyon(usrmsg).generate()
if result == False:
bot.edit_message_text(
"Can't get images right now. Try again", message.chat.id, temp.message_id
)
else:
path = os.listdir("generated")
print("new images downloaded.")
for item in path:
with open(f"generated/{item}", "rb") as file:
bot.send_photo(message.chat.id, file, item.split(".webp")[0])
print(f"sent images to User '{name}' ({user.usrid})")
unlock()
else:
bot.reply_to(message, "Another user is using this feature. wait...")
# Runs the bot in infinity mode
if __name__ == "__main__":
try:
bot.infinity_polling()
except KeyboardInterrupt:
print("Exit requested by user.")
sys.exit()