-
Notifications
You must be signed in to change notification settings - Fork 1
/
bot.js
224 lines (184 loc) · 5.37 KB
/
bot.js
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
#!/usr/bin/env node
/*!
* Image Creator Bot
* Copyright (c) 2023
*
* @author Zubin
* @username (GitHub) losparviero
* @license AGPL-3.0
*/
// Add env vars as a preliminary
import dotenv from "dotenv";
dotenv.config();
import { Bot, session, GrammyError, HttpError } from "grammy";
import { hydrateReply, parseMode } from "@grammyjs/parse-mode";
import { run, sequentialize } from "@grammyjs/runner";
import { hydrate } from "@grammyjs/hydrate";
import { Configuration, OpenAIApi } from "openai";
// Bot
const bot = new Bot(process.env.BOT_TOKEN);
// Auth
const configuration = new Configuration({
apiKey: process.env.API_KEY,
});
const openai = new OpenAIApi(configuration);
// Concurrency
function getSessionKey(ctx) {
return ctx.chat?.id.toString();
}
// Plugins
bot.use(sequentialize(getSessionKey));
bot.use(session({ getSessionKey }));
bot.use(responseTime);
bot.use(log);
bot.use(admin);
bot.use(hydrate());
bot.use(hydrateReply);
// Parse
bot.api.config.use(parseMode("Markdown"));
// Admin
const admins = process.env.BOT_ADMIN?.split(",").map(Number) || [];
async function admin(ctx, next) {
ctx.config = {
botAdmins: admins,
isAdmin: admins.includes(ctx.chat?.id),
};
await next();
}
// Response
async function responseTime(ctx, next) {
const before = Date.now();
await next();
const after = Date.now();
console.log(`Response time: ${after - before} ms`);
}
// Log
async function log(ctx, next) {
let message = ctx.message?.text || ctx.channelPost?.text || undefined;
const from = ctx.from || ctx.chat;
const name =
`${from.first_name || ""} ${from.last_name || ""}`.trim() || ctx.chat.title;
// Console
console.log(
`From: ${name} (@${from.username}) ID: ${from.id}\nMessage: ${message}`
);
// Channel
let logId = process.env.BOT_ADMIN || process.env.LOG_CHANNEL;
if (
ctx.message &&
!ctx.message?.text?.includes("/") &&
!admins.includes(ctx.chat?.id) &&
logId
) {
await bot.api.sendMessage(
logId,
`<b>From: ${name} (@${from.username}) ID: <code>${from.id}</code></b>`,
{ parse_mode: "HTML" }
);
await ctx.api.forwardMessage(logId, ctx.chat.id, ctx.message.message_id);
}
await next();
}
// Commands
bot.command("start", async (ctx) => {
await ctx
.reply("*Welcome!* ✨\n_Describe the picture that you want to create._")
.then(console.log("New user added:\n", ctx.from));
});
bot.command("help", async (ctx) => {
await ctx
.reply(
"*@anzubo Project.*\n\n_This bot generates images using text prompts.\nIt uses OpenAI's DALL-E generations API._"
)
.then(console.log("Help command sent to", ctx.chat.id));
});
// Messages
bot.on("message:text", async (ctx) => {
const statusMessage = await ctx.reply(`*Creating*`);
let response;
try {
async function consultGPT(ctx) {
try {
const resultPromise = await openai.createImage({
prompt: ctx.message.text,
n: 1,
size: "1024x1024",
});
const result = await Promise.race([
resultPromise,
new Promise((_, reject) => {
setTimeout(() => {
reject("Function timeout");
}, 60000);
}),
]);
let image_url = result.data.data[0].url;
await ctx.replyWithPhoto(image_url, {
reply_to_message_id: ctx.message.message_id,
caption: `<b>Image for</b> <code>${ctx.message.text}</code>\n<i>Generated using <b><a href= "https://t.me/makepicbot">Image Creator</a></b></i>`,
parse_mode: "HTML",
});
} catch (error) {
if (error === "Function timeout") {
await ctx.reply("*Query timed out.*", {
parse_mode: "Markdown",
reply_to_message_id: ctx.message.message_id,
});
} else {
throw error;
}
}
}
await consultGPT(ctx);
await statusMessage.delete();
// Error
} catch (error) {
if (error instanceof GrammyError) {
if (error.message.includes("Forbidden: bot was blocked by the user")) {
console.log("Bot was blocked by the user");
} else if (error.message.includes("Call to 'sendMessage' failed!")) {
console.log("Error sending message: ", error);
await ctx.reply(`*Error contacting Telegram.*`, {
reply_to_message_id: ctx.message.message_id,
});
} else {
await ctx.reply(`*An error occurred: ${error.message}*`, {
reply_to_message_id: ctx.message.message_id,
});
}
console.log(`Error sending message: ${error.message}`);
return;
} else {
console.log(`An error occured:`, error);
await ctx.reply(`*An error occurred.*\n_Error: ${error.message}_`, {
reply_to_message_id: ctx.message.message_id,
});
return;
}
}
});
// Error
bot.catch((err) => {
const ctx = err.ctx;
console.error(
"Error while handling update",
ctx.update.update_id,
"\nQuery:",
ctx.msg.text
);
const e = err.error;
if (e instanceof GrammyError) {
console.error("Error in request:", e.description);
if (e.description === "Forbidden: bot was blocked by the user") {
console.log("Bot was blocked by the user");
} else {
ctx.reply("An error occurred");
}
} else if (e instanceof HttpError) {
console.error("Could not contact Telegram:", e);
} else {
console.error("Unknown error:", e);
}
});
// Run
run(bot);