-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
106 lines (97 loc) · 2.75 KB
/
index.ts
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
// import { serve } from "https://deno.land/[email protected]/http/server.ts";
console.log(`Function "telegram-bot" up and running!`);
import {
Bot,
webhookCallback,
} from "https://deno.land/x/[email protected]/mod.ts";
import {
CoinListType,
CurrencyListType,
getCurrenciesAndCoins,
} from "./bonbast.ts";
const bot = new Bot(Deno.env.get("TELEGRAM_KEY") || "");
bot.command("start", (ctx) =>
ctx.reply("Hello. get the latest currencies in Toman"),
);
bot.command("get", async (ctx) => {
const user = await ctx.getAuthor();
if (!Deno.env.get("USERS")!.split(",").includes(user.user.username!)) {
console.log("*******", user.user.username, "*****", Deno.env.get("USERS"));
return ctx.reply("Scram! You're not allowed to use this bot.");
}
try {
const result = await getCurrenciesAndCoins();
if (result?.currencyList && result?.coinList) {
return ctx.reply(
makeCurrencyTable(result.currencyList).concat(
makeCoinTable(result.coinList),
),
{ parse_mode: "MarkdownV2" },
);
}
return ctx.reply("Something went wrong!");
} catch (error) {
console.error(JSON.stringify(error, null, 2));
return ctx.reply(error.message);
}
});
const handleUpdate = webhookCallback(bot, "std/http");
Deno.serve(async (req) => {
if (req.method === "POST") {
return await handleUpdate(req);
// const url = new URL(req.url);
// console.log(url)
// if (url.pathname.slice(1) === bot.token) {
// try {
// } catch (err) {
// console.error(err);
// }
// }
}
return new Response();
});
function rightpad(text: string, length: number): string {
return text.concat(Array.from({ length: length - text.length }).join(" "));
}
function makeCurrencyTable(currencies: CurrencyListType[]): string {
const data = currencies
.map(
(item) =>
`| ${rightpad(item.currency, 20)} | ${rightpad(item.buy, 10)} | ${rightpad(
item.sell,
10,
)} | \n`,
)
.join("");
return (
"```\n" +
`| ${rightpad("Currency", 20)} | ${rightpad("Buy", 10)} | ${rightpad(
"Sell",
10,
)} |\n| :------------------ | --------- | --------- |\n${data}\n`
.replace(/\|/g, "\\|")
.replace(/\-/g, "\\-") +
"```"
);
}
function makeCoinTable(coins: CoinListType[]): string {
const data = coins
.map(
(item) =>
`| ${rightpad(item.coin, 8)} | ${rightpad(item.buy, 15)} | ${rightpad(
item.sell,
15,
)} | \n`,
)
.join("");
return (
"```\n" +
`| ${rightpad("Coin", 8)} | ${rightpad("Buy", 15)} | ${rightpad(
"Sell",
15,
)} |\n| :------ | -------------- | -------------- |\n${data}\n`
.replace(/\|/g, "\\|")
.replace(/\-/g, "\\-") +
"```"
);
}