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
import thisval from "https://esm.town/v/begoon/thisval";
import { env } from "node:process";
const { BOT_TOKEN, ME } = env;
const TELEGRAM = `https://api.telegram.org`;
const BOT = `${TELEGRAM}/bot${BOT_TOKEN}`;
const VAL = thisval();
const { endpoint } = VAL;
import { OpenAI } from "https://esm.town/v/std/openai";
const openai = new OpenAI();
async function POST(cmd: string, data: { [key: string]: string }) {
const url = BOT + "/" + cmd;
return await (await fetch(
url,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
},
)).json();
}
async function GET(cmd: string) {
return await (await fetch(BOT + "/" + cmd)).json();
}
async function sendMessage(chat_id: string, text: string) {
return await POST("sendMessage", { chat_id, text });
}
async function setWebhook(url: string) {
return await POST("setWebhook", { url });
}
async function getWebhookInfo() {
return await GET("getWebhookInfo");
}
export default async function(req: Request): Promise<Response> {
const url = new URL(req.url);
const path = url.pathname;
const me = req.headers.get("ME");
if (me === ME) {
if (path === "/env") return Response.json(env);
if (path === "/val") return new Response(JSON.stringify(VAL));
if (path === "/endpoint") return new Response(JSON.stringify({ endpoint }));
if (path === "/webhook") return Response.json(await getWebhookInfo());
if (path === "/webhook/set") return Response.json(await setWebhook(endpoint + "/bot"));
}
if (path === "/bot") {
const update = await req.json();
console.log("update", update);
const { message } = update;
const { text, from } = message;
const { id } = from;
if (message && text) {
console.log("message", { text, from, id });
let reply = "asking " + text + "?";
if (text.startsWith("/ai")) {
const q = text.split(" ").slice(1).join(" ");
console.log("q", q);
const completion = await openai.chat.completions.create({
messages: [
{ role: "user", content: q },
],
model: "gpt-4",
max_tokens: 30,
});
reply = completion.choices[0].message.content;
console.log({ reply });
}
await sendMessage(id, reply);
}
return Response.json({ ok: true });
}
if (path === "/message") {
const user_id = url.searchParams.get("chat_id");
const text = url.searchParams.get("text");
console.log({ user_id, text });
if (!user_id || !text) return Response.json({ error: "missing user_id or text" });
return Response.json(await sendMessage(user_id, text));
}
return Response.json({ error: "ha?" });
}