Last active
May 20, 2019 23:16
-
-
Save mpociot/1305e7590c3f1c2cc3824ae91441fbdc to your computer and use it in GitHub Desktop.
Use BotMan to link between multiple messenger services
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use App\Channel; | |
use App\Http\Controllers\BotManController; | |
use BotMan\BotMan\Drivers\DriverManager; | |
use BotMan\Drivers\Slack\SlackDriver; | |
use BotMan\Drivers\Slack\SlackRTMDriver; | |
use BotMan\Drivers\Telegram\TelegramDriver; | |
use BotMan\Drivers\Web\WebDriver; | |
$botman = resolve('botman'); | |
$botman->group(['driver' => TelegramDriver::class], function ($botman) { | |
$botman->hears('(.*)', function ($bot, $input) { | |
// Save username | |
$user = $bot->getUser(); | |
$channelName = 'telegram-message-'.str_slug($user->getUsername()); | |
// Change to Slack Driver | |
$bot->loadDriver(SlackDriver::class); | |
// Create a new slack channel with the admin token | |
$channel = $bot->sendRequest('channels.join', [ | |
'token' => env('SLACK_ADMIN_TOKEN'), | |
'name' => $channelName | |
]); | |
// Retrieve the channel id | |
$channelId = array_get(json_decode($channel->getContent(), true), 'channel.id'); | |
// Join the channel with the bot | |
$channel = $bot->sendRequest('channels.invite', [ | |
'token' => env('SLACK_ADMIN_TOKEN'), | |
'channel' => $channelId, | |
'user' => env('SLACK_BOT_ID') | |
]); | |
// Save Telegram -> Slack user mapping in database | |
$channel = Channel::firstOrCreate([ | |
'channel_id' => $channelId, | |
'telegram_id' => $user->getId() | |
]); | |
if ($channel->wasRecentlyCreated) { | |
// Notify slack channel (only once) | |
$bot->say('New message from '.$user->getFirstName().' - join <#'.$channelId.'>', env('SLACK_CHANNEL_ID'), SlackDriver::class, [ | |
'as_user' => false, | |
'username' => $user->getFirstName().' via Telegram' | |
]); | |
} | |
// Originate the original message to the new channel. | |
$bot->say($input, $channelId, SlackDriver::class, [ | |
'as_user' => false, | |
'username' => $user->getFirstName().' via Telegram' | |
]); | |
}); | |
}); | |
$botman->group(['driver' => SlackRTMDriver::class], function ($botman) { | |
$botman->hears('(.*)', function ($bot, $input) { | |
// Send the reply back to telegram, if it's in a channel that belongs to a Telegram user. | |
$channel = Channel::where('channel_id', $bot->getMessage()->getPayload()->get('channel'))->first(); | |
if ($channel) { | |
$bot->say($input, $channel->telegram_id, TelegramDriver::class); | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment