Skip to content

Commit 042b095

Browse files
authored
Merge pull request #13 from AleksandrSherehkov/master
feat: implemented support for report commands (/bug, /idea, /typo, /n…
2 parents 90bf993 + 7acc5c2 commit 042b095

File tree

2 files changed

+107
-26
lines changed

2 files changed

+107
-26
lines changed

dreamland.js

+40-9
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,12 @@ class DreamLand {
2222
constructor(bottype) {
2323
this.bottype = bottype;
2424
this.token = process.env.DREAMLAND_TOKEN;
25+
this.types = {
26+
bug: { url: '/bug', title: '_Баг-репорт:_\n\n' },
27+
typo: { url: '/typo', title: '_Друкарська помилка:_\n\n' },
28+
idea: { url: '/idea', title: '_Ідея:_\n\n' },
29+
nohelp: { url: '/nohelp', title: '_Відсутність розділу довідки:_\n\n' },
30+
};
2531
}
2632

2733
body(args) {
@@ -32,6 +38,31 @@ class DreamLand {
3238
return { method: 'POST', body: JSON.stringify(this.body(args)) };
3339
}
3440

41+
async sendReport(type, args) {
42+
const escapeMarkdown = text => {
43+
return text.replace(/([_*[\]()~`>#+\-=|{}.!])/g, '\\$1');
44+
};
45+
46+
const { url, title } = this.types[type];
47+
const response = await enqueueToDream(`${api}${url}`, this.options(args));
48+
49+
let result;
50+
51+
if (response.ok) {
52+
const { id, message } = args;
53+
54+
result =
55+
`${title}` +
56+
`*Відправник:* ${escapeMarkdown(id)}\n` +
57+
`*Текст:* ${escapeMarkdown(message)}\n\n` +
58+
`${title.trim()} успішно надіслано.`;
59+
} else {
60+
result = `Цей користувач Telegram не повʼязан з жодним персонажем. Використовуй *'режим телеграм'* у грі.`;
61+
}
62+
63+
return result;
64+
}
65+
3566
async who() {
3667
const args = { message: '' };
3768
const response = await enqueueToDream(`${api}/who`, this.options(args));
@@ -40,12 +71,12 @@ class DreamLand {
4071
let result = '';
4172

4273
if (who.total === 0) {
43-
result = 'В мире никого нет!';
74+
result = 'У світі нікого немає!';
4475
} else {
4576
result = '```';
4677
if (who.people && who.people.length > 0)
4778
result +=
48-
'\nСейчас в мире:\n\n' +
79+
'\nЗараз у світі:\n\n' +
4980
who.people
5081
.map(
5182
p =>
@@ -58,10 +89,10 @@ class DreamLand {
5889

5990
if (who.discord && who.discord.length > 0)
6091
result +=
61-
'\n\nСлышат каналы: ' +
92+
'\n\nЧують канали: ' +
6293
who.discord.map(p => p.name.ru || p.name.en).join(', ');
6394

64-
result += '\n\nВсего игроков: ' + who.total + '.\n```';
95+
result += '\n\nУсього гравців: ' + who.total + '.\n```';
6596
}
6697

6798
return result;
@@ -109,10 +140,10 @@ class DreamLand {
109140
if (response.ok) result = undefined;
110141
else if (response.status === 404)
111142
result =
112-
'Ты не присоединен ни к одному персонажу. Зайди в DreamLand и набери config ' +
143+
'Ти не приєднаний до жодного персонажа. Зайди в DreamLand і набери config' +
113144
this.bottype +
114145
'.';
115-
else result = 'Произошла ошибка, попробуй позже.';
146+
else result = 'Відбулася помилка, спробуй пізніше.';
116147

117148
return result;
118149
}
@@ -121,13 +152,13 @@ class DreamLand {
121152
const response = await enqueueToDream(`${api}/link`, this.options(args));
122153
let result;
123154

124-
if (response.ok) result = 'Успешно присоединен к персонажу.';
155+
if (response.ok) result = 'Успішно приєднано до персонажа.';
125156
else if (response.status === 404)
126157
result =
127-
'Персонажа с таким секретным словом не существует. Зайди в DreamLand и набери config ' +
158+
'Персонажу з таким секретним словом немає. Зайди в DreamLand і набери config' +
128159
this.bottype +
129160
'.';
130-
else result = 'Произошла ошибка, попробуй позже.';
161+
else result = 'Відбулася помилка, спробуй пізніше.';
131162

132163
return result;
133164
}

telegram/index.js

+67-17
Original file line numberDiff line numberDiff line change
@@ -10,32 +10,82 @@ const fetch = require('node-fetch');
1010
// 'start' - standard bot command
1111
bot.start(ctx =>
1212
ctx.reply(
13-
'Привет, я Хассан и я скоро поумнею. Набери /help для списка команд.'
13+
'Привіт, я Хасан і я скоро порозумнішаю. Набери /help для списку команд.'
1414
)
1515
);
1616

1717
// 'help' command, can be reworked to show action buttons
1818
bot.help(ctx =>
1919
ctx.reply(
20-
'/who - показать кто в мире\n' +
21-
'/cat - случайный котик\n' +
22-
'/cat says/meow meow - кот с надписью\n' +
23-
'/cat hat/says/hello - кот с тегом hat и надписью\n' +
24-
'/cat gif - анимированный кот\n' +
25-
'/cat says/hello?color=orange - кот с надписью оранжевым цветом\n' +
26-
'/cat says/aloha?color=red&filter=sepia - кот с надписью красным цветом в сепии\n' +
27-
' доступны опции:\n' +
28-
' color - цвет текста;\n' +
29-
' size - размер шрифта;\n' +
20+
'/who - показати хто в світі\n' +
21+
'/who [імʼя] - інформація про конкретного гравця\n' +
22+
'/bug - відправити баг-репорт\n' +
23+
'/typo - повідомити про друкарську помилку\n' +
24+
'/idea - відправити ідею\n' +
25+
'/nohelp - повідомити про відсутність розділу допомоги\n' +
26+
'/cat - випадковий котик\n' +
27+
'/cat says/meow meow - кіт з написом\n' +
28+
'/cat hat/says/hello - кіт з тегом hat і написом\n' +
29+
'/cat gif - анімований кіт\n' +
30+
'/cat says/hello?color=orange - кіт з написом помаранчевим кольором\n' +
31+
'/cat says/aloha?color=red&filter=sepia - кіт з написом червоним кольором в сепії\n' +
32+
' доступні опції:\n' +
33+
' color - колір тексту;\n' +
34+
' size - розмір шрифту;\n' +
3035
' type - тип картинки (small, medium, square, original);\n' +
31-
' filter - фильтр (blur,mono,sepia,negative,paint,pixel);\n' +
32-
' width|height - ширина или высота картинки в пикселях;\n' +
33-
'Подробности в https://cataas.com/'
36+
' filter - фільтр (blur,mono,sepia,negative,paint,pixel);\n' +
37+
' width|height - ширина або висота картинки в пікселях;\n' +
38+
'Деталі на https://cataas.com/'
3439
)
3540
);
3641

3742
bot.use(commandArgsMiddleware());
3843

44+
bot.command('bug', async ctx => {
45+
await handleReportCommand(ctx, 'bug');
46+
});
47+
48+
bot.command('typo', async ctx => {
49+
await handleReportCommand(ctx, 'typo');
50+
});
51+
52+
bot.command('idea', async ctx => {
53+
await handleReportCommand(ctx, 'idea');
54+
});
55+
56+
bot.command('nohelp', async ctx => {
57+
await handleReportCommand(ctx, 'nohelp');
58+
});
59+
60+
async function handleReportCommand(ctx, type) {
61+
const args = ctx.state.command.args;
62+
63+
if (!args || typeof args !== 'string' || args.trim() === '') {
64+
return ctx.reply(
65+
`Будь ласка, вкажіть опис після команди /${ctx.state.command.command}.`
66+
);
67+
}
68+
69+
const userId = ctx.from.username
70+
? `@${ctx.from.username}`
71+
: ctx.from.first_name;
72+
73+
const reportData = {
74+
id: userId,
75+
message: args,
76+
};
77+
78+
try {
79+
const response = await dreamland.sendReport(type, reportData);
80+
ctx.replyWithMarkdown(response);
81+
} catch (error) {
82+
console.error('Помилка під час надсилання повідомлення:', error);
83+
ctx.reply(
84+
'Сталася помилка під час надсилання повідомлення. Спробуйте пізніше.'
85+
);
86+
}
87+
}
88+
3989
bot.command('who', async ctx => {
4090
const args = { message: ctx.state.command.args };
4191

@@ -61,7 +111,7 @@ bot.catch(err => {
61111
console.log(err);
62112
});
63113

64-
// 'cat' command for my dear Tahi.
114+
// 'cat' command for my dear Tahi.
65115
const parser = (str, numb) => {
66116
let result = '';
67117
let matches = str.match(
@@ -120,9 +170,9 @@ bot.command('cat', async ctx => {
120170
}
121171

122172
if (response.status === 404)
123-
return ctx.reply('Неправильный запрос, читайте /help');
173+
return ctx.reply('Неправильний запит читайте /help');
124174

125-
return ctx.reply('Какая-то ошибка, попробуйте позже.');
175+
return ctx.reply('Якась помилка, спробуйте пізніше.');
126176
});
127177

128178
bot.launch();

0 commit comments

Comments
 (0)