Skip to content

Commit 906e74b

Browse files
committed
Add the use of the /pic command to generate images, and add support for the dall-e-3 model
1 parent 09bd5fc commit 906e74b

File tree

3 files changed

+90
-0
lines changed

3 files changed

+90
-0
lines changed

bot.py

+43
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,47 @@ async def search(update, context, title, robot):
193193
result = re.sub(r",", ',', result)
194194
await context.bot.edit_message_text(chat_id=update.message.chat_id, message_id=messageid, text=escape(result), parse_mode='MarkdownV2', disable_web_page_preview=True)
195195

196+
async def image(update, context):
197+
print("\033[32m", update.effective_user.username, update.effective_user.id, update.message.text, "\033[0m")
198+
if (len(context.args) == 0):
199+
message = (
200+
f"格式错误哦~,示例:\n\n"
201+
f"`/pic 一只可爱长毛金渐层在趴在路由器上`\n\n"
202+
f"👆点击上方命令复制格式\n\n"
203+
)
204+
await context.bot.send_message(chat_id=update.effective_chat.id, text=escape(message), parse_mode='MarkdownV2', disable_web_page_preview=True)
205+
return
206+
message = ' '.join(context.args)
207+
result = ""
208+
robot = config.dallbot
209+
text = message
210+
message = await context.bot.send_message(
211+
chat_id=update.message.chat_id,
212+
text="生成中💭",
213+
parse_mode='MarkdownV2',
214+
reply_to_message_id=update.message.message_id,
215+
)
216+
messageid = message.message_id
217+
218+
try:
219+
for data in robot.dall_e_3(text):
220+
result = data
221+
await context.bot.delete_message(chat_id=update.message.chat_id, message_id=messageid)
222+
await context.bot.send_photo(chat_id=update.message.chat_id, photo=result, reply_to_message_id=update.message.message_id)
223+
except Exception as e:
224+
print('\033[31m')
225+
print("response_msg", result)
226+
print("error", e)
227+
traceback.print_exc()
228+
print('\033[0m')
229+
if "You exceeded your current quota, please check your plan and billing details." in str(e):
230+
print("OpenAI api 已过期!")
231+
await context.bot.delete_message(chat_id=update.message.chat_id, message_id=messageid)
232+
messageid = ''
233+
config.API = ''
234+
result += f"`出错啦!{e}`"
235+
print(result)
236+
196237
import time
197238
import threading
198239
async def delete_message(update, context, messageid, delay=10):
@@ -512,6 +553,7 @@ def setup(token):
512553

513554
run_async(application.bot.set_my_commands([
514555
BotCommand('info', 'basic information'),
556+
BotCommand('pic', 'Generate image'),
515557
BotCommand('search', 'search Google or duckduckgo'),
516558
BotCommand('en2zh', 'translate to Chinese'),
517559
BotCommand('zh2en', 'translate to English'),
@@ -521,6 +563,7 @@ def setup(token):
521563
]))
522564

523565
application.add_handler(CommandHandler("start", start))
566+
application.add_handler(CommandHandler("pic", image))
524567
application.add_handler(CommandHandler("search", lambda update, context: search(update, context, title=f"`🤖️ {config.GPT_ENGINE}`\n\n", robot=config.ChatGPTbot)))
525568
application.add_handler(CallbackQueryHandler(button_press))
526569
application.add_handler(CommandHandler("reset", reset_chat))

chatgpt2api/chatgpt2api.py

+45
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,51 @@ def get_filtered_keys_from_object(obj: object, *keys: str) -> Set[str]:
5555
"claude-2",
5656
]
5757

58+
class Imagebot:
59+
def __init__(
60+
self,
61+
api_key: str,
62+
timeout: float = None,
63+
):
64+
self.api_key: str = api_key
65+
self.engine: str = "dall-e-3"
66+
self.session = requests.Session()
67+
self.timeout: float = timeout
68+
69+
def dall_e_3(
70+
self,
71+
prompt: str,
72+
model: str = None,
73+
**kwargs,
74+
):
75+
url = (
76+
os.environ.get("API_URL").split("chat")[0] + "images/generations"
77+
or "https://api.openai.com/v1/images/generations"
78+
)
79+
headers = {"Authorization": f"Bearer {kwargs.get('api_key', self.api_key)}"}
80+
81+
json_post = {
82+
"model": os.environ.get("IMAGE_MODEL_NAME") or model or self.engine,
83+
"prompt": prompt,
84+
"stream": True,
85+
"n": 1,
86+
"size": "1024x1024",
87+
}
88+
response = self.session.post(
89+
url,
90+
headers=headers,
91+
json=json_post,
92+
timeout=kwargs.get("timeout", self.timeout),
93+
stream=True,
94+
)
95+
if response.status_code != 200:
96+
raise t.APIConnectionError(
97+
f"{response.status_code} {response.reason} {response.text}",
98+
)
99+
for line in response.iter_lines():
100+
json_data = json.loads(line.decode("utf-8"))
101+
url = json_data["data"][0]["url"]
102+
yield url
58103

59104
class Chatbot:
60105
"""

config.py

+2
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,11 @@
2121
systemprompt = f"You are ChatGPT, a large language model trained by OpenAI. Knowledge cutoff: 2021-09. Current date: [ {Current_Date} ]"
2222

2323
from chatgpt2api.chatgpt2api import Chatbot as GPT
24+
from chatgpt2api.chatgpt2api import Imagebot
2425
if API:
2526
ChatGPTbot = GPT(api_key=f"{API}", engine=GPT_ENGINE, system_prompt=systemprompt, temperature=temperature)
2627
Claude2bot = GPT(api_key=f"{API}", engine="claude-2-web")
28+
dallbot = Imagebot(api_key=f"{API}")
2729
else:
2830
ChatGPTbot = None
2931

0 commit comments

Comments
 (0)