Skip to content

Commit

Permalink
enhance telegram message
Browse files Browse the repository at this point in the history
add condition to handle unwanted log messages
  • Loading branch information
Rec0gnice committed Sep 3, 2021
1 parent a530fd0 commit 9b04563
Show file tree
Hide file tree
Showing 8 changed files with 98 additions and 43 deletions.
3 changes: 2 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ module.exports = {
],
rules: {
"no-underscore-dangle": 'off',
"space-in-parens": 'warn'
"space-in-parens": 'warn',
"array-bracket-spacing": 'warn'
},
};
14 changes: 7 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"keyv": "^4.0.3",
"mongoose": "^5.12.7",
"node-rdkafka": "^2.10.1",
"node-telegram-bot-api": "^0.53.0",
"node-telegram-bot-api": "^0.54.0",
"tslib": "^2.2.0",
"winston": "^3.3.3",
"winston-transport-sentry-node": "^1.0.2"
Expand Down
21 changes: 11 additions & 10 deletions src/commands/admin/init-exam-channel.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,34 @@
/* eslint-disable linebreak-style */
import { Message } from 'discord.js';
import { WarningMessageEmbed } from '@/embeds';
import { getMessage, logger, keyv } from '@/utils';
import { Message } from 'discord.js';

export default {
name: 'init-exam-channel',
guildOnly: true,
cooldown: 0,
permissions: ['ADMINISTRATOR'],
execute(message: Message) {
permissions: [ 'ADMINISTRATOR' ],
execute( message: Message ) {
const channelId = message.content.split( ' ' )[1];
const examChannel = message.guild?.channels.cache.get( channelId );

function isInvalid() {
return !(channelId && message.guild?.channels.cache.get(channelId));
return !( channelId && examChannel );
}

if (isInvalid()) {
if ( isInvalid() ) {
message.reply(
new WarningMessageEmbed(
{
description: getMessage('command.exams.invalid') + message.content,
description: getMessage( 'command.exams.invalid' ) + message.content,
},
),
);
logger.warn(`Invalid Channel ID: "${message.content}" provided`);
logger.warn( `Invalid Channel ID: "${message.content}" provided` );
return;
}
const key = keyv('exams');
key.set('channel_id', channelId);
logger.info(`New Exam Channel ID: "${channelId}" have been persisted`);
const key = keyv( 'exams' );
key.set( 'channel_id', channelId );
logger.info( `New Exam Channel ID: "${channelId}" have been persisted` );
},
};
43 changes: 31 additions & 12 deletions src/events/exams.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
/* eslint-disable linebreak-style */
import { SuccessMessageEmbed, WarningMessageEmbed } from '@/embeds';
import { getMessage, logger, keyv } from '@/utils';
import { Message } from 'discord.js';
import { SuccessMessageEmbed, WarningMessageEmbed, ErrorMessageEmbed } from '@/embeds';
import { getMessage, logger, keyv } from '@/utils';

import { sendMessage } from '@/extensions/telegram-bot';
import TelegramBot from '@/extensions/telegram-bot';

function acceptRequest( acceptedMessage: Message ) {
return acceptedMessage.reply(
Expand All @@ -25,7 +25,21 @@ function rejectRequest( rejectedMessage: Message ) {
);
}

async function evaluate( message: Message ): Promise< boolean | undefined > {
function sendErrorEmbed( message: Message ) {
return message.reply(
new ErrorMessageEmbed(
{
description: getMessage( 'command.exams.send_error' ),
},
),
);
}

const deleteOptions = {
timeout: 30000,
};

async function evaluate( message: Message ): Promise< boolean | undefined | null > {
const examChannelId = await keyv( 'exams' ).get( 'channel_id' );

if ( !examChannelId ) {
Expand All @@ -37,28 +51,33 @@ async function evaluate( message: Message ): Promise< boolean | undefined > {
const pattern = /(höma|höhere|hö\sma|mathe)+/gi;
const isRequestNotStupid = !( message.cleanContent.match( pattern ) );

const deleteOptions = {
timeout: 30000,
};

const replyMessage = isRequestNotStupid
? await acceptRequest( message ) : await rejectRequest( message );
replyMessage.delete( deleteOptions );
return isRequestNotStupid;
}
return undefined;
return null;
}

export default async function examHandler( message: Message ) {
const result = await evaluate( message );
if ( typeof result === 'undefined' ) {
logger.error( 'Exam evaluation returned an unexpected error' );
logger.error( 'Message evaluation for exams returned an unexpected error' );
return;
}
if ( result === null ) {
// message was sent in different channel
return;
}
if ( result ) {
try {
sendMessage( message );
logger.info( 'A message has been send to Telegram feed' );
const returnCode = await TelegramBot.sendMessage( message );
if ( returnCode === -1 ) {
const errorMessage = await sendErrorEmbed( message );
errorMessage.delete( deleteOptions );
} else {
logger.info( 'A message has been send to Telegram feed' );
}
} catch ( error ) {
logger.error( `Sending message to Telegram Feed failed!\n' + ${error}` );
}
Expand Down
50 changes: 41 additions & 9 deletions src/extensions/telegram-bot.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,51 @@
/* eslint-disable linebreak-style */
import { Message } from 'discord.js';
import environment from '@/environment';
import { Message } from "discord.js";
import { logger } from '@/utils';

const TelegramBot = require( 'node-telegram-bot-api' );

const botConfig = {
polling: true
}
polling: true,
};

const bot = new TelegramBot( environment.telegram_bot_token, botConfig );

async function sendMessage( msg: Message ) {
const completeMessage = 'Eine neue Anfrage wurde auf dem Discord Server registriert:\n\n' + msg.cleanContent;
bot.sendMessage( environment.telegram_feed_id, completeMessage );
}
async function sendMessage( msg: Message ): Promise< number > {
// there is no i18n usage here because of only german recipients
const formattedDate = msg.createdAt
.toLocaleString(
'de-DE',
// creating a seperate object and assign it as param somehow doesn't work
{
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
},
);
const channelName = msg.guild?.channels.cache.get( msg.channel.id )?.name;
const completeMessage = `Eine neue Anfrage wurde auf dem Discord Server im "${channelName}"-Channel registriert:\n\n`
+ `Nickname: ${msg.author.username}\nUser: ${msg.author.tag}\nID: ${msg.author.id}\nZeitstempel: ${formattedDate} Uhr\n\n`
+ `Nachricht (${msg.id}):\n\n"${msg.cleanContent}"\n\n`
+ `Folge dem Link, um direkt zur Nachricht zu gelangen:\n${msg.url}`;
try {
bot.sendMessage(
environment.telegram_feed_id,
completeMessage,
{
disable_web_page_preview: true,
},
);
} catch ( error ) {
logger.error( `Sending message to the Telegram API failed:\n"${error}"` );

export {
sendMessage
return -1;
}
return 0;
}

export default {
sendMessage,
};
5 changes: 3 additions & 2 deletions src/locales/de-DE.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
"exams": {
"success": "Deine Anfrage wurde aufgenommen und weiter geleitet.",
"not_allowed": "Deine Anfrage entspricht nicht den Möglichkeiten des FSR's!",
"invalid": "Die angegebene Channel ID kann nicht zugeordnet werden! Die Eingabe ist: "
"invalid": "Die angegebene Channel ID kann nicht zugeordnet werden! Die Eingabe ist:\n",
"send_error": "Es tut uns Leid, beim Senden deiner Nachricht ist ein Fehler aufgetreten. Bitte wende dich an einen Admin oder den FSR!"
}
},
"embed": {
Expand All @@ -24,4 +25,4 @@
"error": {
"unknown": "Es ist ein unbekannter Fehler aufgetreten!"
}
}
}
3 changes: 2 additions & 1 deletion src/locales/en-GB.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
"exams": {
"success": "Your request has been accepted and send to the person in charge.",
"not_allowed": "Your request contains content that is outside of the FSR's possibilities!",
"invalid": "The given Channel ID could not be applied to the guild! Your Input is:\n"
"invalid": "The given Channel ID could not be applied to the guild! Your Input is:\n",
"send_error": "We are sorry, there was a problem while sending your message. Please contact an admin or a member of the FSR!"
}
},
"embed": {
Expand Down

0 comments on commit 9b04563

Please sign in to comment.