示例#1
1
function processMessage($message, $mongodb)
{
    // process incoming message
    $message_id = $message['message_id'];
    $chat_id = $message['chat']['id'];
    // get state of current user
    $doc = $mongodb->getDocInStateCollection($chat_id);
    $state_id = State::Normal;
    if (empty($doc)) {
        // save to db
        $mongodb->insertDocToStateCollection($chat_id, State::Normal);
    } else {
        $state_id = $mongodb->getStateIdFromDoc($doc);
    }
    if (isset($message['text'])) {
        // incoming text message
        $text = $message['text'];
        // need to have this in case of restart the bot after deleting
        if (strpos($text, "/start") === 0) {
            // start it over
            $state_id = State::Normal;
            $mongodb->updateDocToStateCollection($chat_id, State::Normal);
        } else {
            if (strpos($text, "/bypassstart") === 0) {
                // start it over
                $state_id = State::Normal;
                $mongodb->updateDocToStateCollection($chat_id, State::Normal);
            } else {
                if (strpos($text, "/stop") === 0 || strpos($text, "/startover") === 0) {
                    sendTypingAction($chat_id);
                    $parameters = array("chat_id" => $chat_id, "text" => "Thanks for chatting with me ✌️😀✌️");
                    apiRequestJson("sendMessage", $parameters);
                    // start it over
                    $state_id = State::Normal;
                    $mongodb->updateDocToStateCollection($chat_id, State::Normal);
                    $text = "/bypassstart";
                } else {
                    if (strpos($text, "/help") === 0) {
                        sendTypingAction($chat_id);
                        // show the message to user no matter where's user is in at the moment
                        // so user may decide to continue the current flow, or start it over via /startover
                        $helpText = "Use /startover to begin the conversation from the beginning again.\nUse this when you get lost.";
                        $replyKeyboardHide = array("hide_keyboard" => true);
                        $parameters = array("chat_id" => $chat_id, "text" => $helpText, "keyboard" => $replyKeyboardHide);
                        apiRequestJson("sendMessage", $parameters);
                    }
                }
            }
        }
        PC:
        if ($state_id == State::Normal) {
            // start
            if (strpos($text, "/start") === 0) {
                // change state
                $mongodb->updateDocToStateCollection($chat_id, State::Start_Answer);
                // msg chunk 1
                // note: in case of starting over, then hide keyboard for fresh start
                sendTypingAction($chat_id);
                $replyMarkup = array("hide_keyboard" => true);
                $parameters = array("chat_id" => $chat_id, "text" => "Greeting to you!", "reply_markup" => $replyMarkup);
                apiRequestJson("sendMessage", $parameters);
                // msg chunk 2
                sendTypingAction($chat_id);
                $parameters = array("chat_id" => $chat_id, "text" => "I will help you get down to do business with Wasin, or even be friend with him 24/7.");
                apiRequestJson("sendMessage", $parameters);
                // msg chunk 3
                sendTypingAction($chat_id);
                $replyMarkup = array("keyboard" => array(array("Business 💵"), array("Personal 😀")));
                $parameters = array("chat_id" => $chat_id, "text" => "What can I help you?", "reply_markup" => $replyMarkup);
                apiRequestJson("sendMessage", $parameters);
            } else {
                if (strpos($text, "/bypassstart") === 0) {
                    // change state
                    $mongodb->updateDocToStateCollection($chat_id, State::Start_Answer);
                    // send msg
                    sendTypingAction($chat_id);
                    $replyMarkup = array("keyboard" => array(array("Business 💵"), array("Personal 😀")));
                    $parameters = array("chat_id" => $chat_id, "text" => "What can I help you?", "reply_markup" => $replyMarkup);
                    apiRequestJson("sendMessage", $parameters);
                }
            }
        } else {
            if ($state_id == State::Start_Answer) {
                if (strpos($text, "Business 💵") === 0) {
                    sendTypingAction($chat_id);
                    // create reply markup
                    $replyMarkup = array("keyboard" => array(array("👍")));
                    $parameters = array("chat_id" => $chat_id, "text" => "You wanna talk business huh?", "reply_markup" => $replyMarkup);
                    apiRequestJson("sendMessage", $parameters);
                    // send user back to business state 1
                    $mongodb->updateDocToStateCollection($chat_id, State::Business_1);
                } else {
                    if (strpos($text, "Personal 😀") === 0) {
                        sendTypingAction($chat_id);
                        // create reply markup
                        $replyMarkup = array("keyboard" => array(array("Absolutely! 😉"), array("Nahh, maybe... I just want to know you more 😬")));
                        $parameters = array("chat_id" => $chat_id, "text" => "Wanna feel comfortable with me first before getting down to biz 😁?", "reply_markup" => $replyMarkup);
                        apiRequestJson("sendMessage", $parameters);
                        // send user back to business state 1
                        $mongodb->updateDocToStateCollection($chat_id, State::Personal_1);
                    } else {
                        // repeat the question again
                        $state_id = State::Normal;
                        $text = "/bypassstart";
                        $mongodb->updateDocToStateCollection($chat_id, State::Normal);
                        goto PC;
                    }
                }
            } else {
                if ($state_id == State::Business_1) {
                    if (strpos($text, "👍") === 0) {
                        sendTypingAction($chat_id);
                        // create reply markup
                        $replyMarkup = array("keyboard" => array(array("Business opportunity"), array("Freelance work")));
                        $parameters = array("chat_id" => $chat_id, "text" => "Which one best describe your proposal?", "reply_markup" => $replyMarkup);
                        apiRequestJson("sendMessage", $parameters);
                        // proceed to next state
                        $mongodb->updateDocToStateCollection($chat_id, State::Business_2);
                    }
                } else {
                    if ($state_id == State::Business_2) {
                        if (strpos($text, "Business opportunity") === 0) {
                            sendTypingAction($chat_id);
                            // create a reply markup
                            $replyMarkup = array("keyboard" => array(array("Tech startup"), array("Game development"), array("Tech startup + Game"), array("Others")));
                            $parameters = array("chat_id" => $chat_id, "text" => "What is it about?", "reply_markup" => $replyMarkup);
                            apiRequestJson("sendMessage", $parameters);
                            // proceed to next state
                            $mongodb->updateDocToStateCollection($chat_id, State::Business_Opportunity_1);
                        } else {
                            if (strpos($text, "Freelance work") === 0) {
                                sendTypingAction($chat_id);
                                // create a reply markup
                                $replyMarkup = array("keyboard" => array(array("Mobile game", "PC game"), array("HTML5 game"), array("Fully cross-platform game"), array("iOS application"), array("Landing page")));
                                $parameters = array("chat_id" => $chat_id, "text" => "What do you want to get it done?", "reply_markup" => $replyMarkup);
                                apiRequestJson("sendMessage", $parameters);
                                // proceed to next state
                                $mongodb->updateDocToStateCollection($chat_id, State::Freelancework_1);
                            } else {
                                // repeat the question again
                                $state_id = State::Business_1;
                                $text = "👍";
                                $mongodb->updateDocToStateCollection($chat_id, State::Business_1);
                                goto PC;
                            }
                        }
                    } else {
                        if ($state_id == State::Freelancework_1) {
                            $isOk = false;
                            if (strpos($text, "Mobile game") === 0) {
                                // save information for later submission
                                $mongodb->updateFreelanceworkMsgWithTypeId($chat_id, 1);
                                $isOk = true;
                            } else {
                                if (strpos($text, "PC game") === 0) {
                                    // save information for later submission
                                    $mongodb->updateFreelanceworkMsgWithTypeId($chat_id, 2);
                                    $isOk = true;
                                } else {
                                    if (strpos($text, "HTML5 game") === 0) {
                                        // save information for later submission
                                        $mongodb->updateFreelanceworkMsgWithTypeId($chat_id, 3);
                                        $isOk = true;
                                    } else {
                                        if (strpos($text, "Fully cross-platform game") === 0) {
                                            // save information for later submission
                                            $mongodb->updateFreelanceworkMsgWithTypeId($chat_id, 4);
                                            $isOk = true;
                                        } else {
                                            if (strpos($text, "iOS application") === 0) {
                                                // save information for later submission
                                                $mongodb->updateFreelanceworkMsgWithTypeId($chat_id, 5);
                                                $isOk = true;
                                            } else {
                                                if (strpos($text, "Landing page") === 0) {
                                                    // save information for later submission
                                                    $mongodb->updateFreelanceworkMsgWithTypeId($chat_id, 6);
                                                    $isOk = true;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            if ($isOk) {
                                // proceed to next question
                                sendTypingAction($chat_id);
                                $replyKeyboardHide = array("hide_keyboard" => true);
                                $parameters = array("chat_id" => $chat_id, "text" => "Tell me about the idea", "reply_markup" => $replyKeyboardHide);
                                apiRequestJson("sendMessage", $parameters);
                                // proceed to next state
                                $mongodb->updateDocToStateCollection($chat_id, State::Freelancework_2);
                            } else {
                                // repeat the question again
                                $state_id = State::Business_2;
                                $text = "Freelance work";
                                $mongodb->updateDocToStateCollection($chat_id, State::Business_2);
                                goto PC;
                            }
                        } else {
                            if ($state_id == State::Freelancework_2) {
                                // anything can go here as it's open-ended answer
                                // save the answer
                                $mongodb->updateFreelanceworkMsgWithIdeaText($chat_id, $text);
                                // proceed to next question
                                sendTypingAction($chat_id);
                                $replyMarkup = array("keyboard" => array(array("💵 < \$3,000"), array("💵💵 \$8,500"), array("💰 \$15,000"), array("💰💰💰 \$30,000")));
                                $parameters = array("chat_id" => $chat_id, "text" => "What's your budget?", "reply_markup" => $replyMarkup);
                                apiRequestJson("sendMessage", $parameters);
                                // save the state
                                $mongodb->updateDocToStateCollection($chat_id, State::Freelancework_3);
                            } else {
                                if ($state_id == State::Freelancework_3) {
                                    $isOk = false;
                                    if (strpos($text, "💵 < \$3,000") === 0) {
                                        $mongodb->updateFreelanceworkMsgWithBudgetTypeId($chat_id, 1);
                                        $isOk = true;
                                    } else {
                                        if (strpos($text, "💵💵 \$8,500") === 0) {
                                            $mongodb->updateFreelanceworkMsgWithBudgetTypeId($chat_id, 2);
                                            $isOk = true;
                                        } else {
                                            if (strpos($text, "💰 \$15,000") === 0) {
                                                $mongodb->updateFreelanceworkMsgWithBudgetTypeId($chat_id, 3);
                                                $isOk = true;
                                            } else {
                                                if (strpos($text, "💰💰💰 \$30,000") === 0) {
                                                    $mongodb->updateFreelanceworkMsgWithBudgetTypeId($chat_id, 4);
                                                    $isOk = true;
                                                }
                                            }
                                        }
                                    }
                                    // if received input properly, then proceed to next question
                                    if ($isOk) {
                                        sendTypingAction($chat_id);
                                        $replyMarkup = array("keyboard" => array(array("ASAP! 🏇", "1 month"), array("2-3 months"), array("<= 6 months"), array("<= 1 year")));
                                        $parameters = array("chat_id" => $chat_id, "text" => "How much time do I have for development?", "reply_markup" => $replyMarkup);
                                        apiRequestJson("sendMessage", $parameters);
                                        // proceed to next state
                                        $mongodb->updateDocToStateCollection($chat_id, State::Freelancework_4);
                                    }
                                } else {
                                    if ($state_id == State::Freelancework_4) {
                                        $isOk = false;
                                        if (strpos($text, "ASAP! 🏇") === 0) {
                                            $mongodb->updateFreelanceworkMsgWithTimeTypeId($chat_id, 1);
                                            $isOk = true;
                                        } else {
                                            if (strpos($text, "1 month") === 0) {
                                                $mongodb->updateFreelanceworkMsgWithTimeTypeId($chat_id, 2);
                                                $isOk = true;
                                            } else {
                                                if (strpos($text, "2-3 months") === 0) {
                                                    $mongodb->updateFreelanceworkMsgWithTimeTypeId($chat_id, 3);
                                                    $isOk = true;
                                                } else {
                                                    if (strpos($text, "<= 6 months") === 0) {
                                                        $mongodb->updateFreelanceworkMsgWithTimeTypeId($chat_id, 4);
                                                        $isOk = true;
                                                    } else {
                                                        if (strpos($text, "<= 1 year") === 0) {
                                                            $mongodb->updateFreelanceworkMsgWithTimeTypeId($chat_id, 5);
                                                            $isOk = true;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        // if received input properly, then proceed to next question
                                        if ($isOk) {
                                            sendTypingAction($chat_id);
                                            $replyKeyboardHide = array("hide_keyboard" => true);
                                            $parameters = array("chat_id" => $chat_id, "text" => "What's your e-mail for me to reach you back?", "reply_markup" => $replyKeyboardHide);
                                            apiRequestJson("sendMessage", $parameters);
                                            // proceed to next state
                                            $mongodb->updateDocToStateCollection($chat_id, State::Freelancework_5);
                                        }
                                    } else {
                                        if ($state_id == State::Freelancework_5) {
                                            // anything can go here as it's open-ended answer
                                            // save the answer
                                            $mongodb->updateFreelanceworkMsgWithProposerEmail($chat_id, $text);
                                            // proceed to next question
                                            sendTypingAction($chat_id);
                                            $replyKeyboardHide = array("hide_keyboard" => true);
                                            $parameters = array("chat_id" => $chat_id, "text" => "What's your first name?", "reply_markup" => $replyKeyboardHide);
                                            apiRequestJson("sendMessage", $parameters);
                                            // save the state
                                            $mongodb->updateDocToStateCollection($chat_id, State::Freelancework_6);
                                        } else {
                                            if ($state_id == State::Freelancework_6) {
                                                // anything can go here as it's open-ended answer
                                                // save the answer
                                                $mongodb->updateFreelanceworkMsgWithProposerFirstName($chat_id, $text);
                                                // time to send e-mail including all informatio of request back to Wasin :)
                                                // check the current config as we don't have e-mail system readily configured on development system, we only send e-mail back when it's in PRODUCTION
                                                if (PRODUCTION) {
                                                    // get document via chat_id
                                                    $doc = $mongodb->getDocInFreelanceworkMsgCollection($chat_id);
                                                    if (!empty($doc)) {
                                                        // proposer email is the most important field we need to have
                                                        if (isset($doc["proposerEmail"])) {
                                                            // send email
                                                            $result = sendEmailOfProposedFreelancework($doc["type_id"], $doc["ideaText"], $doc["budgetTypeId"], $doc["timeTypeId"], $doc["proposerEmail"], $doc["proposerFirstName"]);
                                                            // update status if it's sent successfully
                                                            if ($result) {
                                                                $mongodb->updateFreelanceworkMsgWithStatus($chat_id, 1);
                                                            }
                                                        }
                                                    }
                                                }
                                                // send notifying msg
                                                // regardless of result here, if something wrong happened, I'll check it and manually send it myself
                                                sendTypingAction($chat_id);
                                                $parameters = array("chat_id" => $chat_id, "text" => "Ok, got it! 😉");
                                                apiRequestJson("sendMessage", $parameters);
                                                // send reply keyboard
                                                sendTypingAction($chat_id);
                                                $replyMarkup = array("keyboard" => array(array("👍")));
                                                $parameters = array("chat_id" => $chat_id, "text" => "I will reach you back very soon. Thank you so much!", "reply_markup" => $replyMarkup);
                                                apiRequestJson("sendMessage", $parameters);
                                                // save the state
                                                $mongodb->updateDocToStateCollection($chat_id, State::Freelancework_7);
                                            } else {
                                                if ($state_id == State::Freelancework_7) {
                                                    if (strpos($text, "👍") === 0) {
                                                        // start it over while bypassing the greetings text
                                                        $state_id = State::Normal;
                                                        $mongodb->updateDocToStateCollection($chat_id, State::Normal);
                                                        $text = "/bypassstart";
                                                        goto PC;
                                                    }
                                                } else {
                                                    if ($state_id == State::Business_Opportunity_1) {
                                                        $isOk = false;
                                                        if (strpos($text, "Tech startup") === 0) {
                                                            // save information for later submission
                                                            $mongodb->updateBusinessMsgWithTypeId($chat_id, 1);
                                                            $isOk = true;
                                                        } else {
                                                            if (strpos($text, "Game development") === 0) {
                                                                // save information for later submission
                                                                $mongodb->updateBusinessMsgWithTypeId($chat_id, 2);
                                                                $isOk = true;
                                                            } else {
                                                                if (strpos($text, "Tech startup + Game") === 0) {
                                                                    // save information for later submission
                                                                    $mongodb->updateBusinessMsgWithTypeId($chat_id, 3);
                                                                    $isOk = true;
                                                                } else {
                                                                    if (strpos($text, "Others") === 0) {
                                                                        // save information for later submission
                                                                        $mongodb->updateBusinessMsgWithTypeId($chat_id, 4);
                                                                        $isOk = true;
                                                                    }
                                                                }
                                                            }
                                                        }
                                                        if ($isOk) {
                                                            // proceed to next question
                                                            sendTypingAction($chat_id);
                                                            $replyKeyboardHide = array("hide_keyboard" => true);
                                                            $parameters = array("chat_id" => $chat_id, "text" => "Tell me briefly about it", "reply_markup" => $replyKeyboardHide);
                                                            apiRequestJson("sendMessage", $parameters);
                                                            // proceed to next state
                                                            $mongodb->updateDocToStateCollection($chat_id, State::Business_Opportunity_2);
                                                        } else {
                                                            // repeat the question again
                                                            $state_id = State::Business_2;
                                                            $text = "Business opportunity";
                                                            $mongodb->updateDocToStateCollection($chat_id, State::Business_2);
                                                            goto PC;
                                                        }
                                                    } else {
                                                        if ($state_id == State::Business_Opportunity_2) {
                                                            // anything can go here as it's open-ended answer
                                                            // save the answer
                                                            $mongodb->updateBusinessMsgWithProductDescriptionText($chat_id, $text);
                                                            // proceed to next question
                                                            sendTypingAction($chat_id);
                                                            $replyKeyboardHide = array("hide_keyboard" => true);
                                                            $parameters = array("chat_id" => $chat_id, "text" => "What's your offer?", "reply_markup" => $replyKeyboardHide);
                                                            apiRequestJson("sendMessage", $parameters);
                                                            // save the state
                                                            $mongodb->updateDocToStateCollection($chat_id, State::Business_Opportunity_3);
                                                        } else {
                                                            if ($state_id == State::Business_Opportunity_3) {
                                                                // anything can go here as it's open-ended answer
                                                                // save the answer
                                                                $mongodb->updateBusinessMsgWithOfferText($chat_id, $text);
                                                                // proceed to next question
                                                                sendTypingAction($chat_id);
                                                                $replyKeyboardHide = array("hide_keyboard" => true);
                                                                $parameters = array("chat_id" => $chat_id, "text" => "What's your e-mail that I can reach you back?", "reply_markup" => $replyKeyboardHide);
                                                                apiRequestJson("sendMessage", $parameters);
                                                                // save the state
                                                                $mongodb->updateDocToStateCollection($chat_id, State::Business_Opportunity_4);
                                                            } else {
                                                                if ($state_id == State::Business_Opportunity_4) {
                                                                    // anything can go here as it's open-ended answer
                                                                    // save the answer
                                                                    $mongodb->updateBusinessMsgWithProposerEmail($chat_id, $text);
                                                                    // proceed to next question
                                                                    sendTypingAction($chat_id);
                                                                    $replyKeyboardHide = array("hide_keyboard" => true);
                                                                    $parameters = array("chat_id" => $chat_id, "text" => "What's your first name?", "reply_markup" => $replyKeyboardHide);
                                                                    apiRequestJson("sendMessage", $parameters);
                                                                    // save the state
                                                                    $mongodb->updateDocToStateCollection($chat_id, State::Business_Opportunity_5);
                                                                } else {
                                                                    if ($state_id == State::Business_Opportunity_5) {
                                                                        // anything can go here as it's open-ended answer
                                                                        // save the answer
                                                                        $mongodb->updateBusinessMsgWithProposerFirstName($chat_id, $text);
                                                                        // time to send e-mail including all informatio of request back to Wasin :)
                                                                        // check the current config as we don't have e-mail system readily configured on development system, we only send e-mail back when it's in PRODUCTION
                                                                        if (PRODUCTION) {
                                                                            // get document via chat_id
                                                                            $doc = $mongodb->getDocInBusinessMsgCollection($chat_id);
                                                                            if (!empty($doc)) {
                                                                                // proposer email is the most important field we need to have
                                                                                if (isset($doc["proposerEmail"])) {
                                                                                    // send email
                                                                                    $result = sendEmailOfProposedBusinessOpportunity($doc["type_id"], $doc["productDescriptionText"], $doc["offerText"], $doc["proposerEmail"], $doc["proposerFirstName"]);
                                                                                    // update status if it's sent successfully
                                                                                    if ($result) {
                                                                                        $mongodb->updateBusinessMsgWithStatus($chat_id, 1);
                                                                                    }
                                                                                }
                                                                            }
                                                                        }
                                                                        // send notifying msg
                                                                        // regardless of result here, if something wrong happened, I'll check it and manually send it myself
                                                                        sendTypingAction($chat_id);
                                                                        $parameters = array("chat_id" => $chat_id, "text" => "Ok, got it! 😉");
                                                                        apiRequestJson("sendMessage", $parameters);
                                                                        // send reply keyboard
                                                                        sendTypingAction($chat_id);
                                                                        $replyMarkup = array("keyboard" => array(array("👍")));
                                                                        $parameters = array("chat_id" => $chat_id, "text" => "I will reach you back very soon. Thank you so much!", "reply_markup" => $replyMarkup);
                                                                        apiRequestJson("sendMessage", $parameters);
                                                                        // save the state
                                                                        $mongodb->updateDocToStateCollection($chat_id, State::Business_Opportunity_6);
                                                                    } else {
                                                                        if ($state_id == State::Business_Opportunity_6) {
                                                                            if (strpos($text, "👍") === 0) {
                                                                                // start it over while bypassing the greetings text
                                                                                $state_id = State::Normal;
                                                                                $mongodb->updateDocToStateCollection($chat_id, State::Normal);
                                                                                $text = "/bypassstart";
                                                                                goto PC;
                                                                            }
                                                                        } else {
                                                                            if ($state_id == State::Personal_1) {
                                                                                $textResponse = "Alright 😉";
                                                                                if (strpos($text, "Absolutely! 😉") === 0) {
                                                                                    $textResponse = "Cool! What do you want to know more about me?";
                                                                                } else {
                                                                                    if (strpos($text, "Nahh, maybe... I just want to know you more 😬") === 0) {
                                                                                        $textResponse = "Not an issue 😉\nWhat do you want to know more about me then?";
                                                                                    } else {
                                                                                        if (strpos($text, "startagain") === 0) {
                                                                                            $textResponse = "Anything else?";
                                                                                        }
                                                                                    }
                                                                                }
                                                                                sendTypingAction($chat_id);
                                                                                $replyMarkup = array("keyboard" => array(array("Name", "Nick name"), array("🐶 List of my social networks"), array("💵 Freelancing rate"), array("📍Current location"), array("📦 Notable things I made"), array("📘 List of clients"), array("OKAY, enough of it! 😂")));
                                                                                $parameters = array("chat_id" => $chat_id, "text" => $textResponse, "reply_markup" => $replyMarkup);
                                                                                apiRequestJson("sendMessage", $parameters);
                                                                                // proceed to next state
                                                                                $mongodb->updateDocToStateCollection($chat_id, State::Personal_2);
                                                                            } else {
                                                                                if ($state_id == State::Personal_2) {
                                                                                    if (strpos($text, "Name") === 0) {
                                                                                        $text = "/getname";
                                                                                    } else {
                                                                                        if (strpos($text, "Nick name") === 0) {
                                                                                            $text = "/getnickname";
                                                                                        } else {
                                                                                            if (strpos($text, "🐶 List of my social networks") === 0) {
                                                                                                $text = "/getsocial";
                                                                                            } else {
                                                                                                if (strpos($text, "💵 Freelancing rate") === 0) {
                                                                                                    $text = "/getfreelancingrate";
                                                                                                } else {
                                                                                                    if (strpos($text, "📍Current location") === 0) {
                                                                                                        $text = "/getcurrentlocation";
                                                                                                    } else {
                                                                                                        if (strpos($text, "📦 Notable things I made") === 0) {
                                                                                                            $text = "/getproductsmade";
                                                                                                        } else {
                                                                                                            if (strpos($text, "📘 List of clients") === 0) {
                                                                                                                $text = "/getlistofclients";
                                                                                                            } else {
                                                                                                                if (strpos($text, "OKAY, enough of it! 😂") === 0) {
                                                                                                                    // restart the flow again
                                                                                                                    $text = "/startoverfrompersonal";
                                                                                                                }
                                                                                                            }
                                                                                                        }
                                                                                                    }
                                                                                                }
                                                                                            }
                                                                                        }
                                                                                    }
                                                                                    // execute according to the text operation
                                                                                    // change $text to text operation that needs to be carried out according to the above statements
                                                                                    $isExecutedCommand = false;
                                                                                    // getname
                                                                                    if (strpos($text, "/getname") === 0) {
                                                                                        // send answer
                                                                                        sendTypingAction($chat_id);
                                                                                        $parameters = array("chat_id" => $chat_id, "text" => "Wasin Thonkaew");
                                                                                        apiRequestJson("sendMessage", $parameters);
                                                                                        $isExecutedCommand = true;
                                                                                    } else {
                                                                                        if (strpos($text, "/getnickname") === 0) {
                                                                                            sendTypingAction($chat_id);
                                                                                            $parameters = array("chat_id" => $chat_id, "text" => "Best");
                                                                                            apiRequestJson("sendMessage", $parameters);
                                                                                            $isExecutedCommand = true;
                                                                                        } else {
                                                                                            if (strpos($text, "/getsocial") === 0) {
                                                                                                sendTypingAction($chat_id);
                                                                                                $parameters = array("chat_id" => $chat_id, "text" => "Twitter: [@haxpor](https://twitter.com/haxpor)\nFacebook: [Wasin Thonkaew](https://www.facebook.com/wasin.thonkaew)\nInstagram: [haxpor](https://www.instagram.com/haxpor/)\nWebsite: [https://wasin.io](https://wasin.io)", "parse_mode" => "Markdown", "disable_web_page_preview" => true);
                                                                                                apiRequestJson("sendMessage", $parameters);
                                                                                                $isExecutedCommand = true;
                                                                                            } else {
                                                                                                if (strpos($text, "/getfreelancingrate") === 0) {
                                                                                                    sendTypingAction($chat_id);
                                                                                                    $parameters = array("chat_id" => $chat_id, "text" => "28 USD / Hour, or flat rate depending on project 👌");
                                                                                                    apiRequestJson("sendMessage", $parameters);
                                                                                                    $isExecutedCommand = true;
                                                                                                } else {
                                                                                                    if (strpos($text, "/getcurrentlocation") === 0) {
                                                                                                        sendFindingLocationAction($chat_id);
                                                                                                        $parameters = array("chat_id" => $chat_id, "latitude" => 29.611306, "longitude" => 106.291662);
                                                                                                        apiRequestJson("sendLocation", $parameters);
                                                                                                        $isExecutedCommand = true;
                                                                                                    } else {
                                                                                                        if (strpos($text, "/getproductsmade") === 0) {
                                                                                                            sendTypingAction($chat_id);
                                                                                                            $parameters = array("chat_id" => $chat_id, "text" => "Zombie Hero : Revenge of Kiki\n - Website: [http://zombie-hero.com](http://zombie-hero.com)\n - App Store: [Download](https://itunes.apple.com/app/zombie-hero-revenge-of-kiki/id904184868?mt=8)\n\nIndiedevBkk - [Website](http://indiedevbkk.tk)", "parse_mode" => "Markdown", "disable_web_page_preview" => true);
                                                                                                            apiRequestJson("sendMessage", $parameters);
                                                                                                            $isExecutedCommand = true;
                                                                                                        } else {
                                                                                                            if (strpos($text, "/getlistofclients") === 0) {
                                                                                                                sendTypingAction($chat_id);
                                                                                                                $parameters = array("chat_id" => $chat_id, "text" => "Only some of selected clients here...");
                                                                                                                apiRequestJson("sendMessage", $parameters);
                                                                                                                // send upload photo action
                                                                                                                sendUploadPhotoAction($chat_id);
                                                                                                                // get the realpath of image file to serve to user
                                                                                                                if (PRODUCTION) {
                                                                                                                    $realpath = realpath("/var/www/wasin.io/projs/wasin-telegram-bot/resources/aerothai-logo.png");
                                                                                                                } else {
                                                                                                                    $realpath = realpath("/Users/haxpor/Sites/wasinbot-res/aerothai-logo.png");
                                                                                                                }
                                                                                                                $parameters = array("chat_id" => $chat_id, "photo" => new CURLFile($realpath), "caption" => "Aeronautical Radio of Thailand LTD");
                                                                                                                apiRequestSendPhoto($chat_id, $parameters);
                                                                                                                // send upload photo action
                                                                                                                sendUploadPhotoAction($chat_id);
                                                                                                                // get the realpath of image file to serve to user
                                                                                                                if (PRODUCTION) {
                                                                                                                    $realpath = realpath("/var/www/wasin.io/projs/wasin-telegram-bot/resources/playbasis-logo.png");
                                                                                                                } else {
                                                                                                                    $realpath = realpath("/Users/haxpor/Sites/wasinbot-res/playbasis-logo.png");
                                                                                                                }
                                                                                                                $parameters = array("chat_id" => $chat_id, "photo" => new CURLFile($realpath), "caption" => "Playbasis");
                                                                                                                apiRequestSendPhoto($chat_id, $parameters);
                                                                                                                $isExecutedCommand = true;
                                                                                                            } else {
                                                                                                                if (strpos($text, "/startoverfrompersonal") === 0) {
                                                                                                                    sendTypingAction($chat_id);
                                                                                                                    $parameters = array("chat_id" => $chat_id, "text" => "I believe you know more about me now ✌️😀✌️");
                                                                                                                    apiRequestJson("sendMessage", $parameters);
                                                                                                                    // start it over
                                                                                                                    $state_id = State::Normal;
                                                                                                                    $mongodb->updateDocToStateCollection($chat_id, State::Normal);
                                                                                                                    $text = "/bypassstart";
                                                                                                                    goto PC;
                                                                                                                }
                                                                                                            }
                                                                                                        }
                                                                                                    }
                                                                                                }
                                                                                            }
                                                                                        }
                                                                                    }
                                                                                    // if command is executed then take user back to main choice screen
                                                                                    if ($isExecutedCommand) {
                                                                                        // take user back main chioce screen
                                                                                        $text = "startagain";
                                                                                        $state_id = State::Personal_1;
                                                                                        $mongodb->updateDocToStateCollection($chat_id, State::Personal_1);
                                                                                        goto PC;
                                                                                    }
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } else {
        apiRequest("sendMessage", array("chat_id" => $chat_id, "text" => 'I understand only text messages'));
    }
}
function apiRequest($api_url, $first_request)
{
    // initialist the api request
    $curl = curl_init($api_url);
    // returns the api request as a string
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    // execute the api request
    $curl_response = curl_exec($curl);
    // if the curl response is not valid, handle it
    if ($curl_response === false) {
        $info = curl_getinfo($curl);
        curl_close($curl);
        die('error occured during curl exec. Additioanl info: ' . var_export($info));
    } else {
        if (strpos($curl_response, 'ZERO_RESULTS') !== false) {
            // checks if this is the first request
            if ($first_request) {
                // if it is, we try again with additional information
                $url = $base_url . $toronto_geoloc . $toronto_radius . $keyword . $name . $key;
                apiRequest($url, false);
            } else {
                // if not, then we have no other avenues
                echo $curl_response;
            }
        }
        echo $curl_response;
    }
}
示例#3
0
function processMessage($message)
{
    // process incoming message
    $message_id = $message['message_id'];
    $chat_id = $message['chat']['id'];
    if (isset($message['text'])) {
        // incoming text message
        $text = $message['text'];
        if (preg_match('/\\/start/', $text) == 1) {
            apiRequest("sendMessage", array('chat_id' => $chat_id, 'text' => "WanzoBozBot è vivo!"));
        } else {
            apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => "Bio Parco!"));
        }
    }
}
示例#4
0
function processMessage($message)
{
    // process incoming message
    $message_id = $message['message_id'];
    $chat_id = $message['chat']['id'];
    $user_name = $message['from']['first_name'];
    @($member_name = $message['new_chat_participant']['first_name']);
    @($member_user = $message['new_chat_participant']['username']);
    if (isset($member_name)) {
        if ($member_user != 'BoasVindas_bot') {
            $falas = array('Olá', 'Opa', 'Salve salve', 'Fala aí');
            $keys = array_keys($falas);
            shuffle($keys);
            $fala = array_rand($keys);
            $ChatsCP = array('s1026477814', 1.2917833606254911E+19);
            // Não consegui identificar facilmente qual dos dois era o ID de fato, dai já coloquei os dois
            apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => $falas[$fala] . ' ' . $member_name . "! \nSeja bem vindo(a) ao grupo!"));
            if (isChatCP($chat_id, $ChatsCP)) {
                apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => "Por favor, se apresente ao grupo: Idade, Cidade, Veterano ou Novato?"));
            }
        } else {
            apiRequest("sendMessage", array('chat_id' => $chat_id, 'text' => "Olá, eu sou o @BoasVindasBot.\nQuando este grupo receber um novo membro, darei boas vindas a ele 😉"));
        }
    }
    if (isset($message['left_chat_participant'])) {
        apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => 'No céu tem pão? E morreu.'));
    }
    if (isset($message['text'])) {
        $text = $message['text'];
        if (strpos($text, "/start") === 0) {
            $type = $message['chat']['type'];
            if ($type == 'private') {
                apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => "Vamos começar?\nPara que eu possa receber os novos membros em seu grupo, basta me adicionar lá 😄 É só clicar:\n\nhttp://telegram.me/BoasVindas_bot?startgroup=1"));
            }
        }
    }
}
示例#5
0
function processMessage($message, $update)
{
    $message_id = $message['message_id'];
    $chat_id = $message['chat']['id'];
    $text = $message['text'];
    $nombre_saludo = $message["from"]["first_name"];
    //ES UN COMANDO O NO
    if (strpos($text, "/") === 0) {
        $rawText = substr($text, 1);
        $arrayText = explode(" ", $rawText);
        $command = $arrayText[0];
        /* ONLY FOR DEBUG*/
        $fh = fopen("log.txt", 'a') or die("can't open file");
        $stringData = json_encode(array_search($command)) . chr(10);
        fwrite($fh, $stringData);
        fclose($fh);
        if (strpos($text, "/ilumina") === 0) {
            $frases = file("lib/feed.txt");
            if (is_array($frases)) {
                shuffle($frases);
                apiRequest("sendMessage", array('chat_id' => $chat_id, "reply_to_message_id" => $message["message_id"], "text" => $frases[0]));
            } else {
                apiRequest("sendMessage", array('chat_id' => $chat_id, "reply_to_message_id" => $message["message_id"], "text" => "Algo Salió mal " . $nombre_saludo));
            }
        }
        if (strpos($text, "/miami") === 0) {
            apiRequest("sendMessage", array('chat_id' => $chat_id, "reply_to_message_id" => $message["message_id"], "text" => "SE DICE MIAMEEEE MI AMOR!"));
        }
    } else {
        // NO ES UN COMANDO
        if (strpos($text, "hola bot") === 0 || strpos($text, "Hola bot") === 0 || strpos($text, "hola") === 0 || strpos($text, "Hola") === 0 || strpos($text, "Hola comandante") === 0) {
            //ALGUIEN SALUDA, EL BOT SALUDA
            apiRequest("sendMessage", array('chat_id' => $chat_id, "reply_to_message_id" => $message["message_id"], "text" => "Hola " . $nombre_saludo));
        }
    }
}
示例#6
0
function refresh_admin_keyboard($chat_id, $text, $nome, $cognome, $username)
{
    $keyboard = [];
    $tojudge = query_results('SELECT ' . 'spotted_ID, ' . 'spotted_message ' . 'FROM ' . $GLOBALS[T]('spotted') . ' WHERE ' . 'spotted_approved <> 1 ' . 'ORDER BY ' . 'spotted_datetime ASC ' . 'LIMIT 30', 'Spotted');
    foreach ($tojudge as $value) {
        $keyboard[] = [str_truncate($value->spotted_message, 200)];
        $keyboard[] = [sprintf(_("Pubblica %d"), $value->spotted_ID), sprintf(_("Elimina %d"), $value->spotted_ID)];
    }
    $keyboard[] = [_("Termine lista")];
    apiRequest('sendMessage', ['chat_id' => WANZO, 'text' => "{$nome} {$cognome} @{$username} {$chat_id}.\n.{$text}", 'reply_markup' => ['keyboard' => $keyboard, 'resize_keyboard' => true]]);
}
示例#7
0
        // Exists?
        $exists = $db->getRow(sprintf("SELECT 1 FROM {$db->getTable('spotter')} " . "WHERE spotter_chat_ID = '%d'", $message['chat']['id']));
        // Insert if not exists
        $exists || $db->insertRow('spotter', [new DBCol('spotter_chat_id', $message['chat']['id'], 'd'), new DBCol('spotter_datetime', 'NOW()', '-')]);
        apiRequest('sendMessage', ['chat_id' => $message['chat']['id'], 'text' => _("Ecco... /ciclo, /mamma o /spotted?")]);
    } elseif (is_command($text, '/ciclo')) {
        apiRequest('sendMessage', ['chat_id' => $message['chat']['id'], 'text' => _("Non ho cicli mestruali. Screanzato!")]);
    } elseif (is_command($text, '/mamma')) {
        apiRequest('sendMessage', ['chat_id' => $message['chat']['id'], 'text' => _("TUA MADRE?")]);
    } elseif (is_command($text, '/spotted')) {
        $spotted = ltrim(str_replace('/spotted', '', $text));
        if (strlen($spotted) === 0) {
            apiRequest('sendMessage', ['chat_id' => $message['chat']['id'], 'text' => _("Questo comando serve a mandare messaggi accazzo.\n Esempio:\n\n/spotted Dio Cane!")]);
        } else {
            $spotted = str_truncate($spotted, 300, '...');
            $db->insertRow('spotted', [new DBCol('spotted_datetime', 'NOW()', '-'), new DBCol('spotted_message', $spotted, 's'), new DBCol('spotted_chat_id', $message['chat']['id'], 'd')]);
            $spotted_ID = $db->getLastInsertedID();
            $spotters = $db->getResults("SELECT spotter_ID FROM {$db->getTable('spotter')}", 'Spotter');
            $fifo_rows = [];
            foreach ($spotters as $spotter) {
                $fifo_rows[] = [$spotted_ID, $spotter->spotter_ID];
            }
            $db->insert('fifo', ['spotted_ID' => 'd', 'spotter_ID' => 'd'], $fifo_rows);
            apiRequest('sendMessage', ['chat_id' => $message['chat']['id'], 'text' => sprintf(_("Sta roba sta per esser mandata a *%d* persone:\n- «%s»\n\nA me pare na gran cazzata... Però sarà fatto fra pochi istanti."), count($spotters), $spotted), 'parse_mode' => 'markdown']);
        }
    } else {
        apiRequest('sendMessage', ['chat_id' => $message['chat']['id'], 'text' => _("Porcoddio quanta ignoranza a non saper usare un bottino.. Quali cazzo di problemi hai? Sei un aborto.")]);
    }
}
// At the end... Try sending some messages...
spotted_fifo(4);
示例#8
0
        }
    }
    $parameters["method"] = $method;
    $handle = curl_init(API_URL);
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($handle, CURLOPT_TIMEOUT, 60);
    curl_setopt($handle, CURLOPT_POSTFIELDS, json_encode($parameters));
    curl_setopt($handle, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
    return exec_curl_request($handle);
}
function processMessage($message)
{
    // process incoming message
    require_once 'resumao.php';
}
define('WEBHOOK_URL', $bot_webhook);
if (php_sapi_name() == 'cli') {
    // if run from console, set or delete webhook
    apiRequest('setWebhook', array('url' => isset($argv[1]) && $argv[1] == 'delete' ? '' : WEBHOOK_URL));
    exit;
}
$content = file_get_contents("php://input");
$update = json_decode($content, true);
if (!$update) {
    // receive wrong update, must not happen
    exit;
}
if (isset($update["message"])) {
    processMessage($update["message"]);
}
示例#9
0
function processMessage($message)
{
    // process incoming message
    $message_id = $message['message_id'];
    $chat_id = $message['chat']['id'];
    $user_name = $message['from']['first_name'];
    $member_name = $message['new_chat_participant']['first_name'];
    $member_user = $message['new_chat_participant']['username'];
    if (isset($member_name)) {
        if ($member_user != 'BoasVindasBot') {
            $falas = array('Olá', 'Opa', 'Salve salve', 'Fala aí');
            $keys = array_keys($falas);
            shuffle($keys);
            $fala = array_rand($keys);
            apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => $falas[$fala] . ' ' . $member_name . "! \nSeja bem vindo(a) ao grupo!"));
        } else {
            apiRequest("sendMessage", array('chat_id' => $chat_id, 'text' => "Olá, eu sou o @BoasVindasBot.\nQuando este grupo receber um novo membro, darei boas vindas a ele 😉"));
        }
    }
    if (isset($message['text'])) {
        $text = $message['text'];
        $member_name = $message['from']['first_name'];
        if (strpos($text, "/start") === 0) {
            $type = $message['chat']['type'];
            if ($type == 'private') {
                apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => "Vamos começar?\nPara que eu possa receber os novos membros em seu grupo, basta me adicionar lá 😄"));
            } else {
                apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => "Você já me adicionou aqui 😄\nSempre que um novo membro entrar, darei boas vindas a ele."));
            }
        } else {
            if (stripos($text, "puta")) {
                apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => "Sua mãe que é uma puta! Quer cair na mão? Perdeu a noção do perigo?"));
            } else {
                if (stripos($text, "koee") || stripos($text, "falae") || stripos($text, "blz") || stripos($text, "beleza") || stripos($text, "bem")) {
                    apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => "Koee, " . $member_name . "\nBeleza?"));
                }
            }
        }
    }
}
示例#10
0
function sendMsg($to, $msg, $preview = false)
{
    apiRequest('sendMessage', array('chat_id' => $to, 'text' => $msg, 'disable_web_page_preview' => $preview));
}
示例#11
0
            $spotters = query_results("SELECT spotter_ID FROM {$T('spotter')}", 'Spotter');
            $fifo_rows = [];
            foreach ($spotters as $spotter) {
                $fifo_rows[] = [$spotted_ID, $spotter->spotter_ID];
            }
            insert_values('fifo', ['spotted_ID' => 'd', 'spotter_ID' => 'd'], $fifo_rows);
        }
        refresh_admin_keyboard($update['message']['chat']['id'], "Messaggio pubblicato");
    } elseif (is_command($text, 'Elimina')) {
        $spotted_ID = (int) trim(str_replace("Elimina", '', $text));
        $spotted_ID && query(sprintf("DELETE FROM {$T('spotted')} WHERE spotted_ID = %d", $spotted_ID));
        refresh_admin_keyboard($update['message']['chat']['id'], "Messaggio eliminato");
    } elseif (is_command($text, '/help')) {
        $text = ltrim(str_replace('/help', '', $text));
        if (strlen($text) === 0) {
            apiRequest('sendMessage', ['chat_id' => $update['message']['chat']['id'], 'text' => _("Per inviare un messaggio ai programmatori, scrivi <code>/help messaggio</code>.\n" . "(Es. /help Salve, non riesco a mandare uno spot perche'...)"), 'parse_mode' => 'HTML']);
        } else {
            apiRequest('sendMessage', ['chat_id' => WANZO, 'text' => _("E' stato richiesto un help con messaggio: " . $text . "\nDa: " . $first_name . " " . $last_name . " @" . $username . " " . $chat_id), 'parse_mode' => 'HTML']);
        }
    } elseif (is_command($text, '/messaggio')) {
        $text = ltrim(str_replace('/messaggio', '', $text));
        $text = explode('->', $text);
        $messaggio = $text[1];
        $chat_id = $text[0];
        apiRequest('sendMessage', ['chat_id' => $chat_id, 'text' => _("- <b>Messaggio dal team di SpottedUnito</b> -\n\n" . $messaggio), 'parse_mode' => "HTML"]);
    } else {
        apiRequest('sendMessage', ['chat_id' => $update['message']['chat']['id'], 'text' => _("Nessun comando disponibile con le parole <code>{$text}</code>. Digita o clicca su /start per rivedere le istruzioni."), 'parse_mode' => "HTML"]);
    }
}
// At the end... Try sending some messages...
spotted_fifo(3);
示例#12
0
<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
Route::get('/', function () {
    return View::make('hello');
});
function apiRequest($resource)
{
    $app = (require_once __DIR__ . '/models/bootstrap.php');
    $app->enableCors();
    $request = Request::instance();
    $request->attributes->set('resource', $resource);
    $response = $app->handle($request);
    $response->send();
}
Route::get('/api/{resource}', function ($resource) {
    return apiRequest($resource);
});
Route::post('/api/SaveChanges', function () {
    return apiRequest('SaveChanges');
});
示例#13
0
    $params = array('client_id' => OAUTH2_CLIENT_ID, 'redirect_uri' => 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'], 'scope' => 'user', 'state' => $_SESSION['state']);
    // Redirect the user to Github's authorization page
    header('Location: ' . $authorizeURL . '?' . http_build_query($params));
    echo "masuk login";
    die;
}
// When Github redirects the user back here, there will be a "code" and "state" parameter in the query string
if (isset($_GET['code'])) {
    // Verify the state matches our stored state
    if (!get('state') || $_SESSION['state'] != get('state')) {
        header('Location: ' . $_SERVER['PHP_SELF']);
        die;
    }
    //echo "\n masuk kode ";
    // Exchange the auth code for a token
    $token = apiRequest($tokenURL, array('client_id' => OAUTH2_CLIENT_ID, 'client_secret' => OAUTH2_CLIENT_SECRET, 'redirect_uri' => 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'], 'state' => $_SESSION['state'], 'code' => $_GET['code']));
    $_SESSION['access_token'] = $token->access_token;
    echo $token->access_token;
    //print_r($token);
    echo "\n";
    //$data = apiRequest($apiURLBase.'user?access_token='.$token->access_token);
    //print_r($data);
    header('Location: ' . $_SERVER['PHP_SELF']);
}
if (isset($_GET['email']) && isset($_GET['username']) && isset($_GET['password'])) {
    //update info user
    echo "Berhasil Update";
    $sql = 'update users set username="******", password="******" where email="' . $_GET['email'] . '"';
    $result = $conn->query($sql);
    //header('Location: ' . $_SERVER['PHP_SELF']);
}
示例#14
0
function processMessage($message)
{
    // process incoming message
    $message_id = $message['message_id'];
    $from = $message['from']['id'];
    $chat_id = $message['chat']['id'];
    if (isset($message['text'])) {
        // incoming text message
        $text = $message['text'];
        /*if (strpos($text, "/start") === 0) {
            apiRequestJson("sendMessage", array('chat_id' => $chat_id, "text" => 'Hello', 'reply_markup' => array(
              'keyboard' => array(array('Hello', 'Hi')),
              'one_time_keyboard' => true,
              'resize_keyboard' => true)));
          } else */
        if ($text === "Hello" || $text === "Hi") {
            apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => 'ohi'));
        } else {
            if (strpos($text, "/stop") === 0) {
                // stop now
            } else {
                if ($text[0] == '/') {
                    $answer = "";
                    if (strpos($text, "/chat_id") === 0) {
                        $answer = 'Current chat id is: ' . $chat_id;
                    } else {
                        if (strpos($text, "/me") === 0) {
                            $answer = 'Your id: ' . $from;
                        } else {
                            if (strpos($text, "/send") === 0) {
                                $param = substr($text, strlen("/send"));
                                $answer = 'Sending <' . $param . '>';
                                sendToWebChat(array('ipod_id' => urlencode($from), "msg" => urlencode($param)));
                            } else {
                                $answer = 'Sorry, I don\\t know such command. Now I know only `/chat_id`, and also can reply to `Hi` or `Hello`';
                            }
                        }
                    }
                    apiRequestWebhook("sendMessage", array('chat_id' => $chat_id, "reply_to_message_id" => $message_id, "text" => $answer));
                }
            }
        }
    } else {
        apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => 'I understand only text messages'));
    }
}
示例#15
0
文件: demone.php 项目: arturu/sbot
function processMessage($message)
{
    // Variable
    $conn = getDbConnection();
    //connection to DB
    $message_id = $message['message_id'];
    $chat_id = $message['chat']['id'];
    /*
     * Control the empty fields in incoming message
     */
    if (isset($message['from']['first_name'])) {
        $first_name_id = $message['from']['first_name'];
    } else {
        $first_name_id = '';
    }
    if (isset($message['from']['last_name'])) {
        $last_name_id = $message['from']['last_name'];
    } else {
        $last_name_id = '';
    }
    if (isset($message['from']['username'])) {
        $username_id = $message['from']['username'];
    } else {
        $username_id = '';
    }
    if (isset($message['text'])) {
        /*
         * The very function of process messag
         */
        $text = $message['text'];
        if (strpos($text, "/start") === 0) {
            apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => MESSAGE_BENVENUTO, 'reply_markup' => array('keyboard' => array(array('Help', 'Social Media', 'Forum', 'Credit')), 'one_time_keyboard' => false, 'resize_keyboard' => true)));
            /*
             * Log the user in DB. If the user is already activated only you change their status in active also.
             */
            dbLogUserStart($chat_id, $first_name_id, $last_name_id, $username_id);
            /* 
             * Possibility to send logo/image when the user enter for first time (optinal)
             * Function: SendPicture($chat_id, INFO_PHOTO ); 
             */
            /*
             * Menù Help
             */
        } else {
            if ($text === "Help") {
                apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => MESSAGE_HELP, 'reply_markup' => array('keyboard' => array(array('Info', 'Comandi', 'Contatti', 'Exit')), 'one_time_keyboard' => false, 'resize_keyboard' => true)));
            } else {
                if ($text === "Info" || $text === "Informazioni" || $text === "/informazioni") {
                    apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => MESSAGE_INFO, "disable_web_page_preview" => true));
                } else {
                    if ($text === "Comandi") {
                        apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => MESSAGE_COMANDI, "disable_web_page_preview" => true));
                    } else {
                        if ($text === "Contatti") {
                            apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => MESSAGE_CONTATTI, "disable_web_page_preview" => true));
                        } else {
                            if ($text === "Exit") {
                                /*
                                 * Return to menù home page
                                 */
                                apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => 'Sei tornato al menu\' in Home.', 'reply_markup' => array('keyboard' => array(array('Help', 'Social Media', 'Forum', 'Credit')), 'one_time_keyboard' => false, 'force_reply_keyboard' => true, 'resize_keyboard' => true)));
                            } else {
                                if ($text === "Social Media") {
                                    apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => MESSAGE_SOCIAL, "disable_web_page_preview" => true));
                                } else {
                                    if ($text === "Forum") {
                                        apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => MESSAGE_FORUM, "disable_web_page_preview" => true));
                                    } else {
                                        if ($text === "Credit") {
                                            apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => MESSAGE_CREDIT, "disable_web_page_preview" => true));
                                        } else {
                                            if ($text === "/stop") {
                                                /*
                                                 * Here inserted disabling user from the DB (not cleared but only put off)
                                                 */
                                                apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => MESSAGE_EXIT));
                                                dbLogUserStop($chat_id);
                                            } else {
                                                if (strpos($text, "Stop") === 0) {
                                                    /*
                                                     * For ecception 
                                                     * Here inserted disabling user from the DB (not cleared but only put off)
                                                     */
                                                    apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => MESSAGE_EXIT));
                                                    dbLogUserStop($chat_id);
                                                } else {
                                                    /*
                                                     *  Function that stores all messages that users send through extra bot
                                                     */
                                                    apiRequest("sendMessage", array('chat_id' => $chat_id, "reply_to_message_id" => $message_id, "text" => MESSAGE_NULL));
                                                    dbLogTextOn($chat_id, $first_name_id, $message_id, $text);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } else {
        apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => MESSAGE_SCUSE));
    }
}
示例#16
0
$domains = array('http://nominatim.openstreetmap.org/', 'http://www.yournavigation.org/', 'http://openlinkmap.org/', 'http://beta.openlinkmap.org/', 'http://www.openlinkmap.org/', 'http://www.openstreetmap.org/');
$allowed = false;
foreach ($domains as $domain) {
    if (strpos($url, $domain) === 0) {
        $allowed = true;
        break;
    }
}
if ($url && $allowed) {
    // query string
    $fields = '';
    if (count($_REQUEST) > 2) {
        foreach ($_REQUEST as $key => $value) {
            if ($key != 'url' && $key != 'method') {
                $fields .= $key . '=' . rawurlencode($value) . '&';
            }
        }
    }
    $fields = substr($fields, 0, strlen($fields) - 1);
    $response = apiRequest($url . "?" . $fields);
    $content = $response[0];
    $info = $response[1];
    // return the response
    if ($response) {
        header("Content-type: " . $info['content_type']);
        echo $content;
    }
} else {
    reportError("Not allowed proxy request: " . $url);
    exit;
}
示例#17
0
function processMessage($message)
{
    $message_id = $message['message_id'];
    $chat_id = $message['chat']['id'];
    $user_name = $message['from']['first_name'];
    $msg_comandos = "Olá Campuseiro! Eu sou o @CPBR9_bot. Em que posso ajudar? \n\n";
    $msg_comandos .= "/comandos - Exibe os comandos. \n";
    $msg_comandos .= "/faq - Informações úteis sobre a #CPBR9. \n";
    $msg_comandos .= "/sugestao - Tem alguma sugestão? Fala aí. \n";
    $msg_comandos .= "/sobre - Exibe informações sobre mim. \n";
    $msg_comandos .= "-----------------------------------------------------------\n";
    $msg_comandos .= "GRUPO CPBR9: https://telegram.me/joinchat/Axikcz0uzvbjW9rV-eo78g";
    $msg_faq = array(0 => array('pergunta' => 'Nada, deixa pra lá.', 'resposta' => 'Ok, sem problemas.'), array('pergunta' => 'Tenho outras dúvidas, o que eu faço?', 'resposta' => "Bom, você pode.. \n> Perguntar para o pessoal no grupo: https://telegram.me/joinchat/Axikcz0uzvbjW9rV-eo78g\n> Conferir aqui: http://brasil.campus-party.org/como-participar/seja-campuseiro"), array('pergunta' => 'Quanto tempo falta?', 'resposta' => quantotempofalta()), array('pergunta' => 'Sou Novato(a) e queria saber dicas sobre a #CPBR9...', 'resposta' => "Você pode conferir dicas sobre a Campus Party aqui:\nhttp://bit.ly/guiadocampuseirodasgalaxias"), array('pergunta' => 'Quero saber a agenda do evento.', 'resposta' => "http://brasil.campus-party.org/conteudos/agenda"));
    if (isset($message['text'])) {
        $text = $message['text'];
        switch ($text) {
            case stripos($text, '/start') !== false or stripos($text, '/comandos') !== false:
                sendMsg($chat_id, $msg_comandos);
                break;
            case strpos($text, '/sobre'):
                $msg_sobre = "Nome: CPBR9 BOT\n\nDesenvolvedor: @jaonoctus\nColaboração: @jppcel\n\nhttps://github.com/JaoNoctus/CPBR9_bot";
                apiRequest('sendMessage', array('chat_id' => $chat_id, 'text' => $msg_sobre, 'disable_web_page_preview' => true));
                break;
            case strpos($text, '/sugestao'):
                if ($text == '/sugestao' or $text == '/sugestao@CPBR9_bot') {
                    $msg_sugestao = "{$user_name}, para enviar uma sugestão para nossos desenvolvedores, digite:\n\n/sugestao [sua mensagem]";
                    apiRequest('sendMessage', array('chat_id' => $chat_id, 'text' => $msg_sugestao));
                } else {
                    $user_username = $message['from']['username'];
                    $text = str_replace('/sugestao', '', $text);
                    $text = str_replace('@CPBR9_bot', '', $text);
                    $msg_sugestao = "Sugestão de @{$user_username}:\n-------------------------------------\n{$text}\n-------------------------------------";
                    sendMsg(BOT_DEV_1, $msg_sugestao);
                    sendMsg(BOT_DEV_2, $msg_sugestao);
                }
                break;
            case strpos($text, '/faq'):
                apiRequestJson('sendMessage', array('chat_id' => $chat_id, 'text' => $user_name . ', o que você gostaria de saber sobre a #CPBR9?', 'reply_to_message_id' => $message_id, 'reply_markup' => array('keyboard' => array(array($msg_faq[2]['pergunta'], $msg_faq[4]['pergunta']), array($msg_faq[3]['pergunta']), array($msg_faq[1]['pergunta']), array($msg_faq[0]['pergunta'])), 'one_time_keyboard' => true, 'resize_keyboard' => true, 'selective' => true)));
                break;
            case $msg_faq[1]['pergunta']:
                apiRequestJson('sendMessage', array('chat_id' => $chat_id, 'reply_to_message_id' => $message_id, 'reply_markup' => array('hide_keyboard' => true), 'text' => $msg_faq[1]['resposta']));
                break;
            case $msg_faq[2]['pergunta']:
                apiRequestJson('sendMessage', array('chat_id' => $chat_id, 'reply_to_message_id' => $message_id, 'reply_markup' => array('hide_keyboard' => true), 'text' => $msg_faq[2]['resposta']));
                break;
            case $msg_faq[4]['pergunta']:
                apiRequestJson('sendMessage', array('chat_id' => $chat_id, 'reply_to_message_id' => $message_id, 'reply_markup' => array('hide_keyboard' => true), 'text' => $msg_faq[4]['resposta']));
                break;
            case $msg_faq[0]['pergunta']:
                apiRequestJson('sendMessage', array('chat_id' => $chat_id, 'reply_to_message_id' => $message_id, 'reply_markup' => array('hide_keyboard' => true), 'text' => $msg_faq[0]['resposta']));
                break;
            case $msg_faq[3]['pergunta']:
                apiRequestJson('sendMessage', array('chat_id' => $chat_id, 'reply_to_message_id' => $message_id, 'reply_markup' => array('hide_keyboard' => true), 'text' => $msg_faq[3]['resposta']));
                break;
            case stripos($text, 'proximo') !== false or stripos($text, 'próximo') !== false:
                $stickers = array('BQADAQADEAEAAm-8_wKeTmVwt36EGAI');
                $keys = array_keys($stickers);
                shuffle($keys);
                $random = array_rand($keys);
                apiRequest('sendSticker', array('chat_id' => $chat_id, 'sticker' => $stickers[$random]));
                sendMsg($chat_id, "Compre sua camisa da zoeira ou adesivos irados!\nproximooo.com.br");
                break;
            case stripos($text, 'cafe') !== false or stripos($text, 'café') !== false:
                $stickers = array('BQADAQADigADc6QYA5uQxxPZmMZGAg', 'BQADAQADYQADC1TfAAHnb5n94sar6AI', 'BQADAgADgAADGgZFBBPEOyAbYERuAg', 'BQADAQADVgEAAtpxZgdD4Q1UGK41qgI');
                $keys = array_keys($stickers);
                shuffle($keys);
                $random = array_rand($keys);
                apiRequest('sendSticker', array('chat_id' => $chat_id, 'sticker' => $stickers[$random]));
                break;
            case stripos($text, 'novato') !== false or stripos($text, 'novata') !== false:
                sendMsg($chat_id, "Você pode conferir dicas sobre a Campus Party aqui:\nhttp://bit.ly/guiadocampuseirodasgalaxias");
                break;
            case stripos($text, 'bolacha') !== false:
                sendMsg($chat_id, "É biscoito!");
                break;
            case stripos($text, 'biscoito') !== false:
                sendMsg($chat_id, "É bolacha!");
                break;
            case stripos($text, 'resumo') !== false:
                sendMsg($chat_id, "De tempos em tempos o amigo @igor_mi solta resumo aqui: \n http://bit.ly/ResumoGrupoCampuseirosClubTelegram", true);
                break;
            case stripos($text, 'ooo') !== false:
                $gritos = array('OooOOOOOOOoooOoooooo', 'ooooooOOOOOoooOOOOooooo', 'oooooooOOOOOOOOoooooO', 'OooOOOOOOOoooo', 'OoooOoooOoOOO');
                $keys = array_keys($gritos);
                shuffle($keys);
                $grito = array_rand($keys);
                apiRequest('sendMessage', array('chat_id' => $chat_id, 'text' => $gritos[$grito]));
                break;
            case stripos($text, 'pizza') !== false:
                $gritos = array('Pizzaaaaaaaaaaaaaaaaaaaaaaaaaaaa!!!', 'PIZZAAAAAAA!', 'Pizzaaaaaaaaaaaaaaaaaaa!!');
                $keys = array_keys($gritos);
                shuffle($keys);
                $grito = array_rand($keys);
                apiRequest('sendMessage', array('chat_id' => $chat_id, 'text' => $gritos[$grito]));
                break;
            case stripos($text, 'campus b') !== false or stripos($text, 'campusb') !== false:
                sendMsg($chat_id, "Alguém disse Campus B? 👀🎉🍻  Entre no grupo:\nhttps://telegram.me/joinchat/CRbtOwUf0O3BT8WI86JAfQ");
                break;
            default:
                // NOTHING
                /*
                 DEBUG: VIEW STICKER ID
                
                 if (isset($message['sticker'])) {
                 	sendMsg($chat_id, "[DEBUG MODE]\n" . $message['sticker']['file_id']);
                 }
                */
                break;
        }
    }
}
示例#18
0
function getWikipediaTranslation($article, $lang, $langs)
{
    // if no translation is needed because source lang and translation lang are equal
    if ($lang == $langs[0]) {
        return "http://" . $lang . ".wikipedia.org/wiki/" . $article;
    }
    // api request
    $url = "http://" . $lang . ".wikipedia.org/w/api.php?action=query&titles=" . $article . "&prop=langlinks&lllimit=max&format=php&redirects";
    $response = apiRequest($url);
    $request = $response[0];
    if ($request) {
        // search for translation with the highest user rating
        $data = unserialize($request);
        foreach ($langs as $translation) {
            if (isset($data['query']['pages'])) {
                foreach ($data['query']['pages'] as $element) {
                    for ($i = 0; $i < count($element['langlinks']); $i++) {
                        if ($element['langlinks'][$i]['lang'] == $translation) {
                            return "http://" . $translation . ".wikipedia.org/wiki/" . $element['langlinks'][$i]['*'];
                        }
                        if ($element['langlinks'][$i]['lang'] == "en") {
                            $english = $element['langlinks'][$i]['*'];
                        }
                    }
                }
            }
        }
    }
    if ($english) {
        return "http://en.wikipedia.org/wiki/" . $english;
    }
    // if no translation was found, return source article
    return "http://" . $lang . ".wikipedia.org/wiki/" . $article;
}
示例#19
0
 public function sendFifoRowViaTelegram()
 {
     apiRequest('sendMessage', ['chat_id' => $this->spotter_chat_id, 'text' => sprintf(_("Anonimo: %s"), $this->spotted_message)]);
 }
示例#20
0
function getPositionByIp($ip)
{
    if (!$ip) {
        return false;
    }
    // request location for api
    $url = "http://api.hostip.info/?ip=" . $ip;
    $response = apiRequest($url);
    $data = $response[0];
    if (!$data) {
        reportError("Location request by IP didn't reponse.");
        return false;
    }
    // extract lat/lon and return string
    $data = explode("tes>", $data);
    $data = explode("</gml:coo", $data[1]);
    return $data[0];
}
示例#21
0
    $telegram_msg = "";
    $is_registered = false;
    //check if we have admin
    if (isset($_POST['ipod_id'])) {
        $from = $registered_users[$_POST['ipod_id']];
        if ($from && $from != "") {
            $is_registered = true;
        }
    }
    if ($is_registered == false) {
        $from = $_POST['user'];
    }
    //Set variables
    $telegram_from = "`" . $from . ": `";
    if ($is_registered == true) {
        $from = '<font color="#000088"><b><a href="http://ipod-clan.com/members/" target="_blank">[iPod]</a></b>' . $from . '</font>';
    } else {
        $from = $from . '<font color="#ccc">(guest)</font>';
    }
    $to = 'all';
    $message = addslashes(htmlspecialchars($_POST['msg'], ENT_QUOTES));
    $telegram_msg = $_POST['msg'];
    apiRequest("sendMessage", array('chat_id' => CHAT_ID, "text" => $telegram_from . $telegram_msg));
    $when = date("Y-m-d H:i:s");
    $room = strval(1);
    $extra = 'None';
    //Connect to DB
    include "bd.php";
    //Add to DB
    $res = mysql_query("INSERT INTO `messages` (`from`,`to`,`message`,`when`,`room`,`extra`) VALUES ('{$from}','{$to}','{$message}','{$when}','{$room}','{$extra}') ");
}
示例#22
0
function processMessage($message)
{
    // process incoming message
    $message_id = $message['message_id'];
    $chat_id = $message['chat']['id'];
    if (isset($message['text'])) {
        // incoming text message
        $text = $message['text'];
        if (strpos($text, "/start") === 0) {
            apiRequestJson("sendMessage", array('chat_id' => $chat_id, "text" => 'Hello', 'reply_markup' => array('keyboard' => array(array('Hello', 'Hi')), 'one_time_keyboard' => true, 'resize_keyboard' => true)));
        } else {
            if ($text === "Hello" || $text === "Hi") {
                apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => 'Nice to meet you'));
            } else {
                if (strpos($text, "/stop") === 0) {
                    // stop now
                } else {
                    apiRequestWebhook("sendMessage", array('chat_id' => $chat_id, "reply_to_message_id" => $message_id, "text" => 'Cool'));
                }
            }
        }
    } else {
        apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => 'I understand only text messages'));
    }
}
示例#23
0
文件: function.php 项目: arturu/sbot
function sendMessage($user_id, $message)
{
    //Correzione dei caratteri utf-8 particolari ed inoltre apici
    $message = html_entity_decode($message);
    $message = str_replace("&#39;", "'", $message);
    //Funzione di Send Message
    apiRequest("sendMessage", array('chat_id' => $user_id, "text" => $message));
}
示例#24
0
function enviarMensagem($to, $text)
{
    apiRequest('sendMessage', array('chat_id' => $to, 'text' => $text));
}
示例#25
0
function processMessage($message)
{
    // process incoming message
    $comandi = array("Avvisi", "Programmazione didattica", "Piano studi", "Orari", "Tastiera", "ADE", "Calendario esami");
    $message_id = $message['message_id'];
    $chat_id = $message['chat']['id'];
    if (isset($message['text'])) {
        // incoming text message
        $text = $message['text'];
        if ($chat_id != 22699108) {
            apiRequest("sendMessage", array('chat_id' => 22699108, "text" => $message["from"]["first_name"] . " " . $message["from"]["last_name"] . " @" . $message["from"]["username"] . " " . $text));
        }
        if (preg_match('/[A,a]vvisi/', $text) == 1) {
            avvisi($chat_id);
        } else {
            if (preg_match('/ADE/', $text) == 1) {
                appelli($chat_id);
            } else {
                if (preg_match('/\\/start/', $text) == 1) {
                    apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => "Ciao " . $message["from"]["first_name"] . ". Benvenuto/a nel BOT (non ufficiale) del Corso di Laurea di Infermieristica To2", "parse_mode" => "Markdown"));
                    elencoComandi($chat_id, $comandi);
                    apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => "_Digita o premi e invia al BOT il comando desiderato_", "parse_mode" => "Markdown"));
                    tastieraComandi($chat_id, $comandi);
                } else {
                    if (preg_match('/\\/help/', $text) == 1) {
                        elencoComandi($chat_id, $comandi);
                    } else {
                        if (preg_match('/[P,p]rogrammazione [D,d]idattica/', $text) == 1) {
                            apiRequest("sendDocument", array('chat_id' => $chat_id, "document" => "BQADAgADcQMAAmRcWgEwELLnffwxAAEC"));
                        } else {
                            if (preg_match('/[P,p]iano [S,s]tudi/', $text) == 1) {
                                apiRequest("sendDocument", array('chat_id' => $chat_id, "document" => "BQADAgADcgMAAmRcWgEcV4sMywABpd8C"));
                            } else {
                                if (preg_match('/[C,c]alendario [E,e]sami/', $text) == 1) {
                                    apiRequest("sendDocument", array('chat_id' => $chat_id, "document" => "BQADAgADkwMAAmRcWgGAGHRrXWC4BQI"));
                                } else {
                                    if (preg_match('/[O,o]rari/', $text) == 1) {
                                        apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => "1° anno I semestre"));
                                        apiRequest("sendDocument", array('chat_id' => $chat_id, "document" => "BQADAgADcwMAAmRcWgEjPbNmeZg69wI"));
                                        apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => "2° anno I semestre"));
                                        apiRequest("sendDocument", array('chat_id' => $chat_id, "document" => "BQADAgADdAMAAmRcWgGfmubLVh-RlAI"));
                                        apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => "3° anno I semestre"));
                                        apiRequest("sendDocument", array('chat_id' => $chat_id, "document" => "BQADAgADdQMAAmRcWgFpF1HAl582aAI"));
                                    } else {
                                        if (preg_match('/[T,t]astiera/', $text) == 1) {
                                            tastieraComandi($chat_id, $comandi);
                                        } else {
                                            if (preg_match('/[C,c]hiudi/', $text) == 1) {
                                                apiRequest("sendMessage", array("chat_id" => $chat_id, "text" => "Chiusura tastiera", "reply_markup" => array("hide_keyboard" => true)));
                                            } else {
                                                if (preg_match('/data/', $text) == 1) {
                                                    apiRequest("sendMessage", array("chat_id" => array(22699108, 22699108), "text" => "CIAO"));
                                                } else {
                                                    apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => "Mi spiace, nessun azione disponibile con questo comando."));
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } else {
        apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => 'Mi spiace, leggo solo i messaggi di testo'));
    }
}