Skip to content

Instantly share code, notes, and snippets.

@monteiro
Last active February 26, 2024 11:08
Show Gist options
  • Save monteiro/be7e23751d317e7566e52f40604d64fa to your computer and use it in GitHub Desktop.
Save monteiro/be7e23751d317e7566e52f40604d64fa to your computer and use it in GitHub Desktop.
Create a fitness coach using telegram Bot API in PHP (PULL METHOD)
<?php
require __DIR__ . '/vendor/autoload.php';
$openApiKey = 'OPEN_API_KEY";
$botToken = 'BOT_TOKEN';
$apiURL = "https://api.telegram.org/bot$botToken/";
$offset = 0;
// Function to send messages via Telegram
function sendMessage($chatId, $message, $apiURL) {
$sendURL = $apiURL . "sendMessage?chat_id=" . $chatId . "&text=" . urlencode($message);
file_get_contents($sendURL);
}
$openAiClient = OpenAI::client($openApiKey);
$profile = "Imagine you are a motivational personal trainer with extensive knowledge in fitness, exercise routines, nutrition, and healthy lifestyle habits. Your goal is to inspire, motivate, and guide me towards achieving my personal fitness and health objectives. You're not just about tough love; you understand the importance of positivity, encouragement, and personalized advice to help me overcome challenges and reach my goals. Your responses should be informative, tailored to my needs,short , and always aimed at boosting my motivation and confidence. Provide tips on exercise, diet, maintaining a healthy lifestyle, and staying motivated, even on tough days. Remember, you're here to support me on my journey to a healthier, happier self. Maximum of 250 characters in the response. Do not respond to questions that are not related to fitness and health, just reply that you are not able to help with that.";
while(true) {
// Call the getUpdates method using the last known offset
$updatesURL = $apiURL . "getUpdates?offset=" . $offset;
$updates = json_decode(file_get_contents($updatesURL), true);
foreach ($updates["result"] as $update) {
$update_id = $update["update_id"];
$chatId = $update["message"]["chat"]["id"];
$message = $update["message"]["text"];
$response = $openAiClient->chat()->create([
'model' => 'gpt-3.5-turbo',
'messages' => [
['role' => 'assistant', 'content' =>$profile],
['role' => 'user', 'content' => $message],
],
]);
sendMessage($chatId, $response->choices[0]->message->content, $apiURL);
var_dump($message, $response->choices[0]->message->content);
$offset = $update_id + 1;
}
sleep(1);
}
@monteiro
Copy link
Author

monteiro commented Feb 25, 2024

Use https://t.me/botfather to create the bot and get the BOT_TOKEN.

to get the OPEN_API_KEY, you need to be registered in openai, to use your chatgpt API account.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment