Skip to content

Commit

Permalink
First release version
Browse files Browse the repository at this point in the history
  • Loading branch information
dmytrohoi committed Sep 10, 2020
1 parent 96ef476 commit 38e422b
Show file tree
Hide file tree
Showing 4 changed files with 323 additions and 0 deletions.
46 changes: 46 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# tg-bridge-pyplugin
[![GitHub](https://img.shields.io/github/license/dmytrohoi/tg-bridge-pyplugin)](https://github.com/dmytrohoi/tg-bridge-pyplugin/blob/master/LICENSE)
[![GitHub release (latest by date)](https://img.shields.io/github/v/release/dmytrohoi/tg-bridge-pyplugin)](https://github.com/dmytrohoi/tg-bridge-pyplugin/releases)
[![GitHub Release Date](https://img.shields.io/github/release-date/dmytrohoi/tg-bridge-pyplugin)](https://github.com/dmytrohoi/tg-bridge-pyplugin/releases)
[![GitHub All Releases](https://img.shields.io/github/downloads/dmytrohoi/tg-bridge-pyplugin/total)](https://github.com/dmytrohoi/tg-bridge-pyplugin/releases)
[![Required](https://img.shields.io/badge/required-PyPlugins-blue)](https://github.com/pyplugins/pyplugins)
[![Spigot](https://img.shields.io/badge/spigot-1.15.2-orange)](https://www.spigotmc.org/resources/telegrambridge.83743/)
[![Spiget Downloads](https://img.shields.io/spiget/downloads/83743)](https://www.spigotmc.org/resources/telegrambridge.83743/)
[![Spiget Stars](https://img.shields.io/spiget/rating/83743)](https://www.spigotmc.org/resources/telegrambridge.83743/)
[![Spiget tested server versions](https://img.shields.io/spiget/tested-versions/83743)](https://www.spigotmc.org/resources/telegrambridge.83743/)
[![bStats Players](https://img.shields.io/bstats/players/8809)](https://www.spigotmc.org/resources/telegrambridge.83743/)
[![bStats Servers](https://img.shields.io/bstats/servers/8809)](https://www.spigotmc.org/resources/telegrambridge.83743/)



## About

Minecraft Spigot plugin on [@pyplugins](https://github.com/pyplugins/pyplugins) interpreter to connect Telegram Bot with Server chat.

This plugin provides messaging between Telegram Chat (through Telegram Bot) and Minecraft Chat.

## Installation

Install [@pyplugins](https://github.com/pyplugins/pyplugins) first (_**required!**_).

[Download latest release](https://github.com/dmytrohoi/tg-bridge-pyplugin/releases) and copy file to `server/plugins/` directory.

Run server.

## Configuration

You can configure the plugin in `/plugins/TelegramBridge/config.yml` file.

## FAQ

### Q: How it's works?

The plugin sends messages using the Telegram Bot API. You just need to set the Telegram Bot Token in config.yml.

To make bridge from Telegram to Minecraft just add RCON connection and command `tg-response <text>` request to your implemented Telegram Bot.


## Donation

If you like it, please use the Sponsor button at the top of this page on GitHub.
Or [liberapay.com](https://liberapay.com/dmytrohoi) / [monobank.ua](https://donate.dmytrohoi.com/).
33 changes: 33 additions & 0 deletions tg-bridge.pyplugin/config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# TelegramBridge v0.0.2 (on PyPlugins https://github.com/pyplugins/pyplugins)
# Link: https://github.com/dmytrohoi/tg-bridge-pyplugin
#
# NOTE: Reload config after changing - /tg-bridge-config reload

## WARNING: Required fields
# Telegram token (https://core.telegram.org/bots#6-botfather)
TOKEN:
# Server chat Telegram ID (https://stackoverflow.com/questions/32423837/telegram-bot-how-to-get-a-group-chat-id)
CHAT_ID:

## TEMPLATES NOTE:
# - available HTML tag (https://core.telegram.org/bots/api#html-style)
# - encode <, > and & symbols to HTML entities - < with &lt;, > with &gt; and & with &amp;
# - use <br/> for newline (aka \n)
# - placeholders: {message_text} and {username} (WARNING: only for outcoming_msg_template and outcoming_msg_broadcast_template)
# - Minecraft formating is available for outcoming_msg_broadcast_template and incoming_msg_template (https://minecraft.gamepedia.com/Formatting_codes)
outcoming_msg_template: '<b>MINECRAFT &lt;{username}&gt;</b>:<br/>{message_text}'
outcoming_msg_broadcast_template: '[ §5Telegram Chat§r §5§l<<§r ] <{username}> {message_text}'
incoming_msg_template: '[ §5Telegram Chat§r §5§l>>§r ] {message_text}'


## Notifications
# The message will be sent to the Telegram chat when the Server starts or shuts down
# Placeholders:
# {ip} - Server IP and Port
# {motd} - Server MOTD
startup_notification:
enable: true
template: "Server {ip} started!"
shutdown_notification:
enable: true
template: "Server {ip} closed."
223 changes: 223 additions & 0 deletions tg-bridge.pyplugin/plugin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@

# /local/bin/python
# -*- coding: utf-8 -*-
"""
Plugin: TelegramBridge (https://github.com/dmytrohoi/tg-bridge-pyplugin)
File: plugin.py
Version: 0.0.2
Author: hedgehoi (Dmytro Hoi)
License: MIT License
Dependencies:
- PyPlugins v0.0.1 / https://github.com/pyplugins/pyplugins
"""
import urllib


class TelegramChatCommands(PythonCommandExecutor):
commands = [
PyCommand('telegram', 'telegramCommand', 'telegramOnTabComplete'),
PyCommand('telegram-chat-response', 'responseCommand', 'telegramOnTabComplete')
]

def telegramCommand(self, sender, command, label, args):
sender_name = sender.getName()
message_text = " ".join(args)
if not message_text:
sender.sendMessage(
self.plugin.placeholder
+ " Please add text to command, for example: /telegram Test"
)
return True

self.plugin.logger.info('{sender} try to send message to Telegram: {message}'.format(
sender=sender_name,
message=message_text
))

template = self.plugin.config.getString(
'outcoming_msg_template',
"{message_text}"
)

# Encode "&", "<" and ">" in message_text
text = template.format(
username=sender_name,
message_text=message_text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
)

result = self.plugin.sendTelegramMessage(text)

if result:
sender.sendMessage(
self.plugin.placeholder
+ " Message sent to Telegram Chat."
)

bc_message = self.plugin.config.getString(
'outcoming_msg_broadcast_template',
"[ Telegram Chat << ] <{username}> {message_text}"
).format(
username=sender_name,
message_text=message_text
)

Bukkit.getServer().broadcastMessage(bc_message)
else:
sender.sendMessage(
self.plugin.placeholder
+ " Message not sent, please call to Server Admins."
)

return True

def responseCommand(self, sender, command, label, args):
message_text = " ".join(args)
if not sender.isOp():
sender.sendMessage(self.plugin.placeholder + " Command only for console usage")
return True

if not message_text:
sender.sendMessage(
self.plugin.placeholder + " Please add text to command, for example: "
"/telegram-chat-response Test"
)
return True

self.plugin.logger.info(
'Console command sent message from Telegram: {message}'.format(
message=message_text
)
)

bc_message = self.plugin.config.getString(
"incoming_msg_template",
"[ Telegram Chat >> ] {message_text}"
).format(message_text=message_text)

Bukkit.getServer().broadcastMessage(bc_message)
sender.sendMessage(self.plugin.placeholder + " Message sent to Minecraft Chat.")
return True

def telegramOnTabComplete(self, sender, command, alias, args):
if len(args) == 1:
return ['<text for message>']
else:
return []


class TelegramBridgePlugin(PythonPlugin):

def onEnable(self):
# Plugin custom placeholder
self.placeholder = u'[ \u00A75tg-bridge\u00A7r ]'
# Add commands
self.apply_command_executor(TelegramChatCommands)

# Add bStats metrics
self.add_bstats(8809)
self.add_configuration(
available_options=[
"outcoming_msg_template",
"outcoming_msg_broadcast_template",
"incoming_msg_template"
]
)
self.logger.info("plugin enabled!")

bot_token = self.config.getString('TOKEN')

if not bot_token:
self.logger.warning(
"Plugin is not configured, please set TOKEN in config.yml"
)

chat_id = self.config.getString('CHAT_ID')
if not chat_id:
self.logger.warning(
"Plugin is not configured, please set CHAT_ID in config.yml"
)
# Startup notification
self.notification("startup_notification")

def onDisable(self):
# Shutdown notification
self.notification("shutdown_notification")

self.logger.info("plugin disabled!")

def notification(self, name):
section = self.config.get(name)
if not section or (section and not section.getBoolean('enable')):
self.logger.info("{} skipped".format(name))
return

self.logger.info("{} option is enabled!".format(name))

template = section.getString(
"template",
"Server {ip} " + "started!" if "start" in name else "stopped!"
)

server = Bukkit.getServer()

# Lazy load placeholders
serverIp = "{}:{}".format(server.getIp(), server.getPort()) if "{ip}" in template else ""
serverMOTD = server.getMotd() if "{motd}" in template else ""

text = template.format(
ip=serverIp,
motd=serverMOTD
)
self.sendTelegramMessage(text)

def sendTelegramMessage(self, text):

chat_id = self.config.getString('CHAT_ID')
bot_token = self.config.getString('TOKEN')

if not chat_id or not bot_token:
self.logger.warning(
"Plugin is not configured, please set CHAT_ID and TOKEN in "
"config.yml"
)
return False

# Make data query for url
data_options = {
'text': text,
'chat_id': chat_id,
'parse_mode': 'HTML'
}

# Replace "<br/>" to new line char
data = urllib.urlencode(data_options).replace("%3Cbr%2F%3E", "%0A")
telegramRequestURL = "https://api.telegram.org/bot{bot_token}/sendMessage?{data}".format(
bot_token=bot_token,
data=data
)

# Send message to Telegram
raw_response = urllib.urlopen(telegramRequestURL)
response = raw_response.read().decode('utf-8')

result = '"ok":true' in response

if result:
self.logger.info(
'Message sent to Telegram: {text}'.format(
text=text
)
)
else:
self.logger.warning(
'Message not sent to Telegram: '
'url="{url}" message="{text}" response="{response}"'.format(
url=telegramRequestURL,
text=text,
response=response
)
)

return result
21 changes: 21 additions & 0 deletions tg-bridge.pyplugin/plugin.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
name: TelegramBridge
main: TelegramBridgePlugin
prefix: tg-bridge
version: 0.0.2
author: hedgehoi
website: https://github.com/dmytrohoi/tg-bridge-pyplugin
commands:
telegram:
description: Send message to Telegram chat
aliases: tg
usage: /&lt;command&gt; &lt;text&gt;

telegram-chat-response:
description: Get response from Telegram Bot (Broadcast message to all players)
aliases: tg-response
permission: minecraft.command.op

tg-bridge-config:
description: Plugin settings
aliases: [tg-config, telegram-config]
permission: minecraft.command.op

0 comments on commit 38e422b

Please sign in to comment.