<commit_before>'use strict';

let https = require('https');
let http = require('http');
let db_query = require('./db');

function setWebhook() {
    let options = {
        host: "api.telegram.org",
        path: `/bot${process.env.TELEGRAM_TOKEN}/setWebhook`,
        method: "POST",
        headers: {
            'Content-Type': "application/json"
        }
    };

    let post_data = {
        url: `https://${process.env.SELF_HOSTNAME}/${process.env.TELEGRAM_TOKEN}`,
        allowed_updates: [ "message" ]
    };

    let post_req = https.request(options, function (res) {
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            console.log('Setting Webhook: ' + chunk);
        });
    });

// post the data
    post_data = JSON.stringify(post_data);
    console.log(JSON.stringify(options));
    console.log(post_data);
    post_req.write(post_data);
    post_req.end();
}

function serverCallback(req, res) {
    if(req.url !== `/${process.env.TELEGRAM_TOKEN}`)
        res.end(JSON.stringify({status: 'not ok', error: 'Wrong request url'}));

    let data='';

    req.on('data', (chunk) => {
        data+=chunk;
    });

    req.on('end', ()=>{
        data = JSON.parse(data);
        try {
            onMessage(data.message, (reply_data, callback)=>{
                try {
                    sendMessage(data.message.chat.id, reply_data.text);
                }catch (err){
                    callback(err);
                }
            });
            res.end(JSON.stringify({status: 'ok'}));
        }catch (err){
            res.end(JSON.stringify(
                {status: 'not ok', error: "Update does not contain message"}));
        }
    });

    req.on('err', (err)=>{
        console.log(err);
        res.end(JSON.stringify({status: 'not ok', error: err}));
    });
}

function onMessage(msg, reply){
    let text = msg.text;
    let chat_id = msg.chat.id;
    try {
        console.log("Command: "+text);
        if (text.indexOf("등록") >= 0) {
            console.log("Opt-in request");
            db_query(1, chat_id, function cb(err, exists) {
                if (err) reply({text: "오류가 발생했습니다. 다시 시도해 주시겠어요?"}, (err) => {
                    if (err) console.log(err);
                });
                else if (exists) reply({text: "이미 등록하셨습니다."}, (err) => {
                    if (err) console.log(err);
                });
                else {
                    let name = msg.from.first_name;
                    let additional_greeting = '';
                    if(name) additional_greeting = `안녕하세요, ${name}님! `;
                    reply({text: additional_greeting+"등록해주셔서 감사합니다. 앞으로 급식/간식 정보를 보내드릴게요!"}, (err) => {
                        if (err) console.log(err)
                    });
                }
            });
        } else if (text.indexOf("해지") >= 0) {
            console.log("Opt-out request");
            db_query(-1, chat_id, function cb(err, exists) {
                if (err) reply({text: "오류가 발생했습니다. 다시 시도해 주시겠어요?"}, (err) => {
                    if (err) console.log(err);
                });
                else if (exists) reply({text: "해지되었습니다. 그동안 이용해 주셔서 감사합니다."}, (err) => {
                    if (err) console.log(err);
                });
                else reply({text: "음...등록하시지 않으셨는데요?"}, (err) => {
                        if (err) console.log(err)
                    });
            });

        }
    }catch (exception){
        reply({text: "꾸?"}, (err) => {
            if (err) console.log(err);
        });
    }
}

function sendMessage(chat_id, text){
    let options = {
        host: "api.telegram.org",
        path: `/bot${process.env.TELEGRAM_TOKEN}/sendMessage`,
        method: "POST",
        headers: {
            'Content-Type': "application/json"
        }
    };

    let post_data = {
        "chat_id": chat_id,
        "text": text<commit_msg>Send reply to /start command<commit_after>'use strict';

let https = require('https');
let http = require('http');
let db_query = require('./db');

function setWebhook() {
    let options = {
        host: "api.telegram.org",
        path: `/bot${process.env.TELEGRAM_TOKEN}/setWebhook`,
        method: "POST",
        headers: {
            'Content-Type': "application/json"
        }
    };

    let post_data = {
        url: `https://${process.env.SELF_HOSTNAME}/${process.env.TELEGRAM_TOKEN}`,
        allowed_updates: [ "message" ]
    };

    let post_req = https.request(options, function (res) {
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            console.log('Setting Webhook: ' + chunk);
        });
    });

// post the data
    post_data = JSON.stringify(post_data);
    console.log(JSON.stringify(options));
    console.log(post_data);
    post_req.write(post_data);
    post_req.end();
}

function serverCallback(req, res) {
    if(req.url !== `/${process.env.TELEGRAM_TOKEN}`)
        res.end(JSON.stringify({status: 'not ok', error: 'Wrong request url'}));

    let data='';

    req.on('data', (chunk) => {
        data+=chunk;
    });

    req.on('end', ()=>{
        data = JSON.parse(data);
        try {
            onMessage(data.message, (reply_data, callback)=>{
                try {
                    sendMessage(data.message.chat.id, reply_data.text);
                }catch (err){
                    callback(err);
                }
            });
            res.end(JSON.stringify({status: 'ok'}));
        }catch (err){
            res.end(JSON.stringify(
                {status: 'not ok', error: "Update does not contain message"}));
        }
    });

    req.on('err', (err)=>{
        console.log(err);
        res.end(JSON.stringify({status: 'not ok', error: err}));
    });
}

function onMessage(msg, reply){
    let text = msg.text;
    let chat_id = msg.chat.id;
    try {
        console.log("Command: "+text);
        if (text.indexOf("등록") >= 0) {
            console.log("Opt-in request");
            db_query(1, chat_id, function cb(err, exists) {
                if (err) reply({text: "오류가 발생했습니다. 다시 시도해 주시겠어요?"}, (err) => {
                    if (err) console.log(err);
                });
                else if (exists) reply({text: "이미 등록하셨습니다."}, (err) => {
                    if (err) console.log(err);
                });
                else {
                    let name = msg.from.first_name;
                    let additional_greeting = '';
                    if(name) additional_greeting = `안녕하세요, ${name}님! `;
                    reply({text: additional_greeting+"등록해주셔서 감사합니다. 앞으로 급식/간식 정보를 보내드릴게요!"}, (err) => {
                        if (err) console.log(err)
                    });
                }
            });
        } else if (text.indexOf("해지") >= 0) {
            console.log("Opt-out request");
            db_query(-1, chat_id, function cb(err, exists) {
                if (err) reply({text: "오류가 발생했습니다. 다시 시도해 주시겠어요?"}, (err) => {
                    if (err) console.log(err);
                });
                else if (exists) reply({text: "해지되었습니다. 그동안 이용해 주셔서 감사합니다."}, (err) => {
                    if (err) console.log(err);
                });
                else reply({text: "음...등록하시지 않으셨는데요?"}, (err) => {
                        if (err) console.log(err)
                    });
            });

        } else if (text === "/start"){
            reply({text: "반갑습니다! 봇의 알림을 받으시려면 등록 이라고 메시지를 보내주세요." +
            " 마음이 바뀌신다면 언제든 해지 라고 메시지를 보내 알림 서비스를 해지하실 수 있습니다."}, (err) => {
                if(err) console.log(err);
            });
        }
    }catch (exception){
        reply({text: "꾸?"}, (err) => {
            if (err) console.log(err);
        });
    }
}

function sendMessage(chat_id, text){
    let options = {
        host: "api.telegram.org",
        path: `/bot${process.env.TELEGRAM_TOKEN}/sendMessage`,
        method: "POST",
        headers: {
            'Content-Type': "application/json"
        }
    };

    let post_data = {
        "chat_id": chat_id,
        "text": text
{'fraction_non_alphanumeric': 0.16415868673050615, 'fraction_numerical': 0.0012436264146250466, 'mean_word_length': 1.6186909801367633, 'pattern_counts': {'":': 4, '<': 3, '<?xml version=': 0, '>': 30, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '541026', 'n_tokens_mistral': 2764, 'n_tokens_neox': 2844, 'n_words': 511}