Back to APIs list

Telegram API examples & templates

Use these vals as a playground to view and fork Telegram API examples and templates on Val Town. Run any example below or find templates that can be used as a pre-built solution.
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
import { sendToTelegram } from "https://esm.town/v/pomdtr/sendToTelegram";
import { secretToTelegramChat } from "https://esm.town/v/pomdtr/secretToTelegramChat";
export async function telegramWelcome(req: express.Request, res: express.Response) {
const { message } = req.body;
let secret: string;
// check if the secret is already set
for (
const [key, chatID] of Object.entries(
secretToTelegramChat,
)
) {
if (chatID == message.from.id) {
secret = key;
break;
}
}
if (secret == "") {
const { nanoid } = await import("npm:nanoid");
secret = nanoid();
secretToTelegramChat[secret] = message.from.id;
}
sendToTelegram(
secret,
`Your Secret is ${secret} - Instructions: https://www.val.town/v/pomdtr.telegram`,
);
}
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
import { telegramSendMessage } from "https://esm.town/v/vtdocs/telegramSendMessage?v=5";
import { fetchTweet } from "https://esm.town/v/dpetrouk/fetchTweet";
import process from "node:process";
export const telegramWebhookEchoMessage = async (
req: express.Request,
res: express.Response,
) => {
// Verify this webhook came from our bot
if (
req.get("x-telegram-bot-api-secret-token") !==
process.env.telegramWebhookSecret
) {
return res.status(401);
}
// Echo back the user's message
const { created_at, text, user } = await fetchTweet(
req.body.message.text,
);
const dateTime = created_at.slice(0, 19).split("T").join(" ");
const messageText = [
[dateTime, `${user.name}${user.screen_name}`].join("\n"),
text.replaceAll(req.body.message.text, ""),
].join("\n\n");
const chatId: number = req.body.message.chat.id;
telegramSendMessage(
process.env.telegramBotToken,
{ chat_id: chatId, text: messageText },
);
};
// Forked from @vtdocs.telegramWebhookEchoMessage
1
2
3
4
5
6
7
8
9
10
11
12
13
import process from "node:process";
import { telegramSetWebhook } from "https://esm.town/v/vtdocs/telegramSetWebhook?v=2";
export const setWebhookExample = telegramSetWebhook(
process.env.telegramBotToken,
{
// Replace this with _your_ web endpoint
url: "https://neverstew-telegramWebhookEchoMessage.web.val.run",
// Optionally, filter what kind of updates you want to receive here
allowed_updates: ["message"],
secret_token: process.env.telegramWebhookSecret,
},
);
1
2
3
4
5
6
7
8
9
import process from "node:process";
import { telegram as telegram2 } from "https://esm.town/v/stevekrouse/telegram?v=4";
export let telegram = (message, options = undefined) =>
telegram2(
process.env.telegram_me,
message,
options,
);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { fetchJSON } from "https://esm.town/v/stevekrouse/fetchJSON?v=41";
export const telegramSetWebhook = async (botToken: string, options: {
url: string;
certificate?: string;
ip_address?: string;
max_connections?: number;
allowed_updates?: string[];
secret_token?: string;
}) =>
fetchJSON(
`https://api.telegram.org/bot${botToken}/setWebhook`,
{
method: "POST",
body: JSON.stringify({ ...options }),
},
);
1
2
3
4
5
6
7
import process from "node:process";
import { telegram } from "https://esm.town/v/stevekrouse/telegram";
export let exampleTelegramMessage = telegram(
process.env.telegram,
{ text: "hi to me on telegram!" },
);
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
import { set } from "https://esm.town/v/std/set?v=11";
import { telegramSendMessage } from "https://esm.town/v/vtdocs/telegramSendMessage?v=5";
import { toBuyDB } from "https://esm.town/v/marcecoll/toBuyDB";
import process from "node:process";
export const telegramWebhookCompra = async (req) => {
// Verify this webhook came from our bot
// Verify this webhook came from our bot
if (
req.headers.get("x-telegram-bot-api-secret-token") !==
process.env.telegramWebhookSecret
) {
return new Response(undefined, { status: 401 });
}
// Echo back the user's message
const body = await req.json();
const text: string = body.message.text;
const chatId: number = body.message.chat.id;
if (text == undefined) {
}
else if (text.startsWith("/addcompra")) {
const item = text.split(" ").slice(1).join(" ");
toBuyDB.push(item);
await telegramSendMessage(
process.env.telegramBotToken,
{ chat_id: chatId, text: `Added "${item}"` },
);
}
else if (text.startsWith("/list")) {
await telegramSendMessage(
process.env.telegramBotToken,
{
chat_id: chatId,
text: `Items:\n * ${toBuyDB.join("\n * ")}`,
},
);
}
else if (text.startsWith("/bought")) {
const count = toBuyDB.length;
while (toBuyDB.length > 0) {
toBuyDB.pop();
}
await telegramSendMessage(
process.env.telegramBotToken,
{
chat_id: chatId,
text: `Cleared ${count} items`,
},
);
}
await set("toBuyDB", toBuyDB);
return new Response(undefined, { status: 200 });
};
// Forked from @vtdocs.telegramWebhookEchoMessage
1
2
3
4
5
6
import process from "node:process";
import { telegramGetMe } from "https://esm.town/v/vtdocs/telegramGetMe";
export const getMeExample = telegramGetMe(
process.env.telegramBotToken,
);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { telegramSendMessage } from "https://esm.town/v/vtdocs/telegramSendMessage?v=5";
import process from "node:process";
export const telegramWebhookEchoMessage = async (req: Request) => {
// Verify this webhook came from our bot
if (
req.headers.get("x-telegram-bot-api-secret-token") !==
process.env.telegramWebhookSecret
) {
return new Response(undefined, { status: 401 });
}
// Echo back the user's message
const body = await req.json();
const text: string = body.message.text;
const chatId: number = body.message.chat.id;
await telegramSendMessage(
process.env.telegramBotToken,
{ chat_id: chatId, text },
);
return Response.json("ok");
};
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
import { fetch } from "https://esm.town/v/std/fetch";
import { email } from "https://esm.town/v/std/email?v=9";
import process from "node:process";
export const sendFoodEmail = async () => {
const randomNumber = Math.floor(Math.random() * 80);
let recipeName = "";
let recipeDescription = "";
let pictureUrl = "";
let videoLink = "";
const url =
"https://tasty.p.rapidapi.com/recipes/list?from=0&size=80&tags=under_30_minutes";
const options = {
method: "GET",
headers: {
"X-RapidAPI-Key": process.env.tastyAPIKey,
"X-RapidAPI-Host": "tasty.p.rapidapi.com",
},
};
try {
const response = await fetch(url, options);
const result = await response.json();
recipeName = result.results[randomNumber].name;
recipeDescription = result.results[randomNumber].description;
pictureUrl = result.results[randomNumber].thumbnail_url;
videoLink = result.results[randomNumber].original_video_url;
}
catch (error) {
console.error(error);
}
let subject = `My daily (fast and yummy) recipe`;
let html = `<h1>${recipeName}</h1>
<p>Heute habe ich folgende Idee:</p>
<p>${recipeDescription}</p>
<img src=${pictureUrl} />
<a href=${videoLink} target="_blank">Video</a>
<p>Dazu ein Glas Chardonnay!
</p>`;
await email({ html, subject });
};
// Forked from @enyo.sendTelegramMessage
1
2
3
4
5
6
7
8
9
10
11
12
13
import process from "node:process";
import { telegramSetWebhook } from "https://esm.town/v/vtdocs/telegramSetWebhook";
export const setWebhookExample = telegramSetWebhook(
process.env.telegramBotToken,
{
// Replace this with _your_ express endpoint
url: "https://api.val.town/v1/express/vtdocs.telegramWebhookEchoMessage",
// Optionally, filter what kind of updates you want to receive here
allowed_updates: ["message"],
secret_token: process.env.telegramWebhookSecret,
},
);
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
import { telegramSendMessage } from "https://esm.town/v/vtdocs/telegramSendMessage?v=5";
import process from "node:process";
import { telegramSendPhoto } from "https://esm.town/v/vtdocs/telegramSendPhoto?v=1";
import { telegramValTownBotSecrets } from "https://esm.town/v/stevekrouse/telegramValTownBotSecrets";
export let telegramValTownBot = async (secret, text, options?) => {
let chat = telegramValTownBotSecrets.find((c) =>
c.secret === secret
);
if (!chat)
throw new Error("@stevekrouse.telegramValTownBot: secret not found");
if (options?.photo) {
telegramSendPhoto(process.env.telegramBot, {
...options,
chat_id: chat.chatId,
});
}
else {
await telegramSendMessage(
process.env.telegramBot,
{
...options,
chat_id: chat.chatId,
text,
},
);
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
import process from "node:process";
import { telegramSetWebhook } from "https://esm.town/v/vtdocs/telegramSetWebhook?v=2";
export const telegramValTownBotWebhookSetup = telegramSetWebhook(
process.env.telegramBot,
{
// Replace this with _your_ express endpoint
url: "https://stevekrouse-telegramValTownBotWebhook.express.val.run",
// Optionally, filter what kind of updates you want to receive here
allowed_updates: ["message"],
secret_token: process.env.telegramWebhookSecret,
},
);
1
2
3
4
5
6
import { fetchJSON } from "https://esm.town/v/stevekrouse/fetchJSON?v=41";
export const telegramGetUpdates = async (botToken: string) =>
fetchJSON(
`https://api.telegram.org/bot${botToken}/getUpdates`,
);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import process from "node:process";
import { telegram } from "https://esm.town/v/stevekrouse/telegram?v=4";
export const canetDeMarResidus = async () => {
const residus = [
"Organica i Envasos",
"Res",
"Organica",
"Rebuig",
"Organica i Envasos",
"Paper i Cartro",
"Organica",
];
const day = new Date().getDay();
const today = residus[day];
return telegram(
process.env.telegram,
`Avui toca: ${today}`,
);
};