Skip to content

Commit

Permalink
Update - you can now subscribe to multiple channels to sync in config…
Browse files Browse the repository at this point in the history
….yml, reinforce code logics
  • Loading branch information
HappyGroupHub committed Jan 24, 2023
1 parent 24940f1 commit 08b3afb
Show file tree
Hide file tree
Showing 4 changed files with 80 additions and 39 deletions.
32 changes: 18 additions & 14 deletions discord_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,21 +23,25 @@ async def on_message(message):
"""Handle message event."""
if message.author == client.user:
return
if message.author.id == utils.get_discord_webhook_id():
if message.author.id in config.get('discord_webhook_bot_ids'):
return
if message.attachments:
for attachment in message.attachments:
if attachment.filename.endswith(('.jpg', '.png', '.jpeg')):
author = message.author.display_name
message = message.content
image_file_path = utils.download_file_from_url(attachment.url, attachment.filename)
line_notify.send_image_message(f"{author}: {message}", image_file_path)
else:
line_notify.send_message(message.content)
elif message.channel.id == int(config.get('discord_channel_id')):
author = message.author.display_name
message = message.content
line_notify.send_message(f"{author}: {message}")
if message.channel.id in config.get('subscribed_discord_channels'):
sub_num = config.get('subscribed_discord_channels').index(message.channel.id) + 1
if message.attachments:
for attachment in message.attachments:
if attachment.filename.endswith(('.jpg', '.png', '.jpeg')):
author = message.author.display_name
message = message.content
image_file_path = utils.download_file_from_url(attachment.url,
attachment.filename)
line_notify.send_image_message(sub_num, f"{author}: {message}", image_file_path)
else:
# TODO(LD): Handle other file types.
pass
else:
author = message.author.display_name
message = message.content
line_notify.send_message(sub_num, f"{author}: {message}")


client.run(config.get('discord_bot_token'))
13 changes: 9 additions & 4 deletions line_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
config = utils.read_config()
line_bot_api = LineBotApi(config.get('line_channel_access_token'))
handler = WebhookHandler(config.get('line_channel_secret'))
discord_webhook = SyncWebhook.from_url(config.get('discord_channel_webhook'))

app = Flask(__name__)
log = create_logger(app)
Expand Down Expand Up @@ -50,12 +49,14 @@ def handle_message(event):
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text=event.source.group_id))
if event.source.group_id == config.get('line_group_id'):
if event.source.group_id in config.get('subscribed_line_channels'):
sub_num = config.get('subscribed_line_channels').index(event.source.group_id) + 1
author = line_bot_api.get_group_member_profile(event.source.group_id,
event.source.user_id).display_name
author_image = line_bot_api.get_group_member_profile(event.source.group_id,
event.source.user_id).picture_url
message = event.message.text
discord_webhook = SyncWebhook.from_url(config.get(f'discord_channel_webhook_{sub_num}'))
discord_webhook.send(message, username=f"{author} - (Line訊息)", avatar_url=author_image)


Expand All @@ -65,13 +66,15 @@ def handle_image(event):
if event.source.type == 'user':
return
if event.source.type == 'group':
if event.source.group_id == config.get('line_group_id'):
if event.source.group_id in config.get('subscribed_line_channels'):
sub_num = config.get('subscribed_line_channels').index(event.source.group_id) + 1
author = line_bot_api.get_group_member_profile(event.source.group_id,
event.source.user_id).display_name
author_image = line_bot_api.get_group_member_profile(event.source.group_id,
event.source.user_id).picture_url
source = line_bot_api.get_message_content(event.message.id)
file_path = utils.download_file_from_line(source, event.message.type)
discord_webhook = SyncWebhook.from_url(config.get(f'discord_channel_webhook_{sub_num}'))
discord_webhook.send(file=File(file_path), username=f"{author} - (Line訊息)",
avatar_url=author_image)

Expand All @@ -82,13 +85,15 @@ def handle_video(event):
if event.source.type == 'user':
return
if event.source.type == 'group':
if config.get('line_chat_type') == 'group':
if event.source.group_id in config.get('subscribed_line_channels'):
sub_num = config.get('subscribed_line_channels').index(event.source.group_id) + 1
author = line_bot_api.get_group_member_profile(event.source.group_id,
event.source.user_id).display_name
author_image = line_bot_api.get_group_member_profile(event.source.group_id,
event.source.user_id).picture_url
source = line_bot_api.get_message_content(event.message.id)
file_path = utils.download_file_from_line(source, event.message.type)
discord_webhook = SyncWebhook.from_url(config.get(f'discord_channel_webhook_{sub_num}'))
discord_webhook.send(file=File(file_path), username=f"{author} - (Line訊息)",
avatar_url=author_image)

Expand Down
10 changes: 6 additions & 4 deletions line_notify.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,27 @@
config = utils.read_config()


def send_message(message):
def send_message(sub_num, message):
"""Send message to LINE Notify.
:param int sub_num: Subscribed sync channels num.
:param str message: Message to send.
"""
token = config.get('line_notify_token')
token = config.get(f'line_notify_token_{sub_num}')
headers = {"Authorization": "Bearer " + token}
data = {'message': message}
requests.post("https://notify-api.line.me/api/notify",
headers=headers, data=data, timeout=5)


def send_image_message(message, image_path):
def send_image_message(sub_num, message, image_path):
"""Send media message to LINE Notify.
:param int sub_num: Subscribed sync channels num.
:param str message: Message to send.
:param str image_path: Path to media.
"""
token = config.get('line_notify_token')
token = config.get(f'line_notify_token_{sub_num}')
headers = {"Authorization": "Bearer " + token}
data = {'message': message}
with open(image_path, 'rb') as image:
Expand Down
64 changes: 47 additions & 17 deletions utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import datetime
import sys
from os.path import exists
from typing import List

import requests
import yaml
Expand All @@ -11,17 +12,30 @@
def config_file_generator():
"""Generate the template of config file"""
with open('config.yml', 'w', encoding="utf8") as f:
f.write("""# Discord-Line-Message-Sync v0.1.4
f.write("""# ++--------------------------------++
# | Discord-Line-Message-Sync v0.1.4 |
# | Made by LD (MIT License) |
# ++--------------------------------++
# Bot tokens and secrets
# You will need to fill in the tokens and secrets for both your Line and Discord bots
Line:
channel_access_token: ''
channel_access_token: '
channel_secret: ''
line_notify_token: ''
group_id: ''
Discord:
bot_token: ''
channel_id: ''
channel_webhook: ''
# Sync channels
# This part will need you to fill in both Line and Discord channel IDs to listen to
# And line notify token, discord channel webhook to send messages.
# These four sets of data will be used to sync messages between Line and Discord
# You can create as many sets of channels as you want to sync
Sync_channels:
1:
line_group_id: ''
line_notify_token: ''
discord_channel_id: ''
discord_channel_webhook: ''
"""
)
sys.exit()
Expand All @@ -37,21 +51,37 @@ def read_config():
"""
if not exists('./config.yml'):
print("Config file not found, create one by default.\nPlease finish filling config.yml")
with open('config.yml', 'w', encoding="utf8") as f:
with open('config.yml', 'w', encoding="utf8"):
config_file_generator()

try:
with open('config.yml', 'r', encoding="utf8") as f:
data = yaml.load(f, Loader=SafeLoader)
subscribed_line_channels: list = []
subscribed_discord_channels: List[int] = []
discord_webhook_bot_ids: List[int] = []
for i in range(1, len(data['Sync_channels']) + 1):
subscribed_line_channels.append(data['Sync_channels'][i]['line_group_id'])
subscribed_discord_channels.append(
int(data['Sync_channels'][i]['discord_channel_id']))
discord_webhook_bot_ids.append(
get_discord_webhook_bot_id(data['Sync_channels'][i]['discord_channel_webhook']))
config = {
'subscribed_line_channels': subscribed_line_channels,
'subscribed_discord_channels': subscribed_discord_channels,
'discord_webhook_bot_ids': discord_webhook_bot_ids,
'line_channel_secret': data['Line']['channel_secret'],
'line_channel_access_token': data['Line']['channel_access_token'],
'line_notify_token': data['Line']['line_notify_token'],
'line_group_id': data['Line']['group_id'],
'discord_bot_token': data['Discord']['bot_token'],
'discord_channel_id': data['Discord']['channel_id'],
'discord_channel_webhook': data['Discord']['channel_webhook']
'discord_bot_token': data['Discord']['bot_token']
}
for i in range(1, len(data['Sync_channels']) + 1):
config['line_group_id_' + str(i)] = data['Sync_channels'][i]['line_group_id']
config['line_notify_token_' + str(i)] = data['Sync_channels'][i][
'line_notify_token']
config['discord_channel_id_' + str(i)] = data['Sync_channels'][i][
'discord_channel_id']
config['discord_channel_webhook_' + str(i)] = data['Sync_channels'][i][
'discord_channel_webhook']
return config
except (KeyError, TypeError):
print(
Expand All @@ -60,12 +90,12 @@ def read_config():
sys.exit()


def get_discord_webhook_id():
"""Get discord webhook id.
def get_discord_webhook_bot_id(webhook_url):
"""Get discord webhook's bot id.
:rtype: int
:param str webhook_url: Discord webhook url.
:return int: Discord webhook's bot id.
"""
webhook_url = read_config().get('discord_channel_webhook')
return int(webhook_url.split('/')[-2])


Expand Down

0 comments on commit 08b3afb

Please sign in to comment.