Skip to content

Commit

Permalink
Add files
Browse files Browse the repository at this point in the history
  • Loading branch information
kamisakihideyoshi committed May 31, 2018
0 parents commit c13604c
Show file tree
Hide file tree
Showing 46 changed files with 1,789 additions and 0 deletions.
Binary file added .DS_Store
Binary file not shown.
1 change: 1 addition & 0 deletions Procfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
web: python app.py
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# nyaa-bot
This is a line bot based on python, with some uselessful function :p
Empty file added __init__.py
Empty file.
2 changes: 2 additions & 0 deletions __main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
from app import main
main()
Binary file added __pycache__/app.cpython-36.pyc
Binary file not shown.
178 changes: 178 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
# coding=UTF-8
# import pkgutil
# import re
# import datetime

import os

import sys
import inspect
import glob
import importlib

import threading
import time
import queue

from modules.base import DataCenter, DataPriority, ModuleData, DataType

from os import listdir
from os.path import dirname, basename

from flask import Flask, request, abort
from linebot import (LineBotApi, WebhookHandler)
from linebot.exceptions import (InvalidSignatureError)
# from linebot.models import * # noqa

from linebot.models import (
MessageEvent,
PostbackEvent
)

from linebot.models import (
Message,
TextMessage,
ImageMessage,
VideoMessage,
AudioMessage,
LocationMessage,
StickerMessage,
FileMessage
)

feedback_queue = queue.PriorityQueue()
user_id_default = 'your user id'
app = Flask(__name__)

# Channel Secret
nyaa_handler = WebhookHandler('your secret')

print('\nLine bot starting OωO')

start_time = time.time()
module_dir = 'modules'
modules_path = glob.glob('./' + module_dir + '/*.py')
modules = []
for path in modules_path:
if path.endswith('__init__.py'):
continue

module = module_dir + '/' + basename(path).replace('.py', '')
modules.append(module.replace('/', '.'))

thread_list = []
queue_list = []

module_number = 0
for module in modules:
importlib.import_module(module)
for name, obj in inspect.getmembers(sys.modules[module]):
if inspect.isclass(obj):
if obj.__module__ == module:
submodule = obj()
if not submodule.__class__.__base__.__name__ == "ModuleBase":
continue
'''
All obj here should inherited from class ModuleBase
init with arguments: main_queue, feedback_queue and tag.
'''
queue_list.append(queue.PriorityQueue())
submodule.set_queue(queue_list[module_number], feedback_queue,
module_number)
thread_list.append(submodule)
module_number += 1

thread_list.append(DataCenter(queue_list, feedback_queue))

for thread in thread_list:
# print(thread)
thread.daemon = True
thread.start()

print('Finish time:', time.time() - start_time, 's.')


@app.route("/callback", methods=['POST'])
def nyaa_callback():
"""Method that monitor all POST requests to nyaa-bot"""
# get X-Line-Signature header value
signature = request.headers['X-Line-Signature']

if signature == 'Wake-up-OwO':
return 'OK'

# get request body as text
body = request.get_data(as_text=True)
app.logger.info("Request body: " + body)

# print('New POST request to nyaa-bot, body:', body)
# print('signature:', signature)

# handle webhook body
try:
nyaa_handler.handle(body, signature)
except InvalidSignatureError:
abort(400)

return 'OK'


@nyaa_handler.add(MessageEvent, message=TextMessage)
def handle_text_message(event):
"""Method that process text massage"""
data = ModuleData(event, data_type=DataType.MESSAGE_TEXT)
feedback_queue.put((DataPriority.MESSAGE, data))


@nyaa_handler.add(MessageEvent, message=ImageMessage)
def handle_image_message(event):
"""Method that process image massage"""
data = ModuleData(event, data_type=DataType.MESSAGE_IMAGE)
feedback_queue.put((DataPriority.MESSAGE, data))


@nyaa_handler.add(MessageEvent, message=VideoMessage)
def handle_video_message(event):
"""Method that process video massage"""
data = ModuleData(event, data_type=DataType.MESSAGE_VIDEO)
feedback_queue.put((DataPriority.MESSAGE, data))


@nyaa_handler.add(MessageEvent, message=AudioMessage)
def handle_audio_message(event):
"""Method that process audio massage"""
data = ModuleData(event, data_type=DataType.MESSAGE_AUDIO)
feedback_queue.put((DataPriority.MESSAGE, data))


@nyaa_handler.add(MessageEvent, message=LocationMessage)
def handle_location_message(event):
"""Method that process location massage"""
data = ModuleData(event, data_type=DataType.MESSAGE_LOCATION)
feedback_queue.put((DataPriority.MESSAGE, data))


@nyaa_handler.add(MessageEvent, message=StickerMessage)
def handle_sticker_message(event):
"""Method that process sticker massage"""
data = ModuleData(event, data_type=DataType.MESSAGE_STICKER)
feedback_queue.put((DataPriority.MESSAGE, data))


@nyaa_handler.add(MessageEvent, message=FileMessage)
def handle_file_message(event):
"""Method that process file massage"""
data = ModuleData(event, data_type=DataType.MESSAGE_FILE)
feedback_queue.put((DataPriority.MESSAGE, data))


@nyaa_handler.add(PostbackEvent)
def handle_postback(event):
"""Method that process postback data"""
data = ModuleData(event, data_type=DataType.POSTBACK)
feedback_queue.put((DataPriority.MESSAGE, data))


if __name__ == "__main__":
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
Binary file added modules/.DS_Store
Binary file not shown.
Empty file added modules/__init__.py
Empty file.
Binary file added modules/__pycache__/__init__.cpython-36.pyc
Binary file not shown.
Binary file added modules/__pycache__/alias.cpython-36.pyc
Binary file not shown.
Binary file added modules/__pycache__/bot_reply.cpython-36.pyc
Binary file not shown.
Binary file added modules/__pycache__/cat_image.cpython-36.pyc
Binary file not shown.
Binary file added modules/__pycache__/catimage.cpython-36.pyc
Binary file not shown.
Binary file added modules/__pycache__/clock.cpython-36.pyc
Binary file not shown.
Binary file added modules/__pycache__/general.cpython-36.pyc
Binary file not shown.
Binary file added modules/__pycache__/module_base.cpython-36.pyc
Binary file not shown.
Binary file added modules/__pycache__/modulebase.cpython-36.pyc
Binary file not shown.
Binary file added modules/__pycache__/qrcode.cpython-36.pyc
Binary file not shown.
Binary file not shown.
Binary file added modules/__pycache__/reply.cpython-36.pyc
Binary file not shown.
Binary file added modules/__pycache__/test_module.cpython-36.pyc
Binary file not shown.
Binary file added modules/__pycache__/testmodule.cpython-36.pyc
Binary file not shown.
71 changes: 71 additions & 0 deletions modules/alias.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# coding=utf-8
import re

from linebot.models import TextSendMessage

from .base import DataType, DataPriority, ModuleBase, ModuleData


class Alias(ModuleBase):
keywords = ['--alias']
alias_list = {}

def run(self):
ModuleBase.run(self)

def text_message_user(self, reply_token, text_message, profile):
if not re.match(r'--alias {1}\w+ {1}\w+', text_message):
reply = 'にゃ? \n(Usage: --alias <user id | group id> <alias you want to set>)'
self.reply(reply_token, TextSendMessage(text=reply))
return

alias_info = text_message.split(' ') # type: list
self.alias_list[alias_info[1]] = alias_info[2]

# Sync alias list to all modules:
self.feedback_queue.put((DataPriority.MODULE, ModuleData(
self.alias_list, data_type=DataType.ALIAS)))

reply = 'にゃー \n(Set alias ' + \
alias_info[2] + ' to ' + alias_info[1] + ')'
self.reply(reply_token, TextSendMessage(text=reply))

def text_message_group(self, reply_token, text_message, profile):
user_name = profile.display_name

if not re.match(r'--alias {1}\w+ {1}\w+', text_message):
reply = '@ ' + user_name + ' にゃ? \n(Usage: --alias' \
' <user id | group id> <alias you want to set>)'
self.reply(reply_token, TextSendMessage(text=reply))
return

alias_info = text_message.split(' ') # type: list
self.alias_list[alias_info[1]] = alias_info[2]

# Sync alias list to all modules:
self.feedback_queue.put((DataPriority.MODULE, ModuleData(
self.alias_list, data_type=DataType.ALIAS)))

reply = '@ ' + user_name + \
' にゃー \n(Set alias ' + alias_info[2] + ' to ' + alias_info[1] + ')'
self.reply(reply_token, TextSendMessage(text=reply))

def text_message_room(self, reply_token, text_message, profile):
user_name = profile.display_name

if not re.match(r'--alias {1}\w+ {1}\w+', text_message):
reply = '@ ' + user_name + ' にゃ? \n(Usage: --alias' \
' <user id | group id> <alias you want to set>)'
self.reply(reply_token, TextSendMessage(text=reply))
return

alias_info = text_message.split(' ') # type: list
self.alias_list[alias_info[1]] = alias_info[2]

# Sync alias list to all modules:
self.feedback_queue.put((DataPriority.MODULE, ModuleData(
self.alias_list, data_type=DataType.ALIAS)))

reply = '@ ' + user_name + \
' にゃー \n(Set alias ' + alias_info[2] + ' to ' + alias_info[1] + ')'
self.reply(reply_token, TextSendMessage(text=reply))
3 changes: 3 additions & 0 deletions modules/base/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from .data import DataType, DataPriority, ModuleData # noqa
from .module import ModuleBase # noqa
from .datacenter import DataCenter # noqa
Binary file added modules/base/__pycache__/__init__.cpython-36.pyc
Binary file not shown.
Binary file added modules/base/__pycache__/data.cpython-36.pyc
Binary file not shown.
Binary file not shown.
Binary file added modules/base/__pycache__/module.cpython-36.pyc
Binary file not shown.
74 changes: 74 additions & 0 deletions modules/base/data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# coding=utf-8
from enum import Enum, auto


class DataType(Enum):
"""The object to indicate the type of data in ModuleData"""

INIT = auto()
REDIRECT = auto()
HELP = auto()
ALIAS = auto()
CLOCK = auto()

POSTBACK = auto()
MESSAGE_TEXT = auto()
MESSAGE_IMAGE = auto()
MESSAGE_VIDEO = auto()
MESSAGE_AUDIO = auto()
MESSAGE_LOCATION = auto()
MESSAGE_STICKER = auto()
MESSAGE_FILE = auto()

REPLY = auto()
PUSH_USER = auto()
PUSH_GROUP = auto()
PUSH_ROOM = auto()


class DataPriority(int):
"""The object to indicate the priority of data for ModuleData"""
SYSTEM = 0
MODULE = 1
MESSAGE = 2


class ModuleData(object):
"""The genaral object used for transfer data between modules."""

def __init__(self,
data=None,
data_type=DataType.MESSAGE_TEXT,
redirect_module: str = None,
module_tag: int = None,
module_name: str = None):
"""The initialization of the object, nothing else to say OωO.
Arguments:
data -- Data to transfer (default None)
data_type -- The type of data (default DataType.MESSAGE_TEXT)
See DataType for all available argments.
redirect_module -- The module name that data redirect to (default None)
Used only when data_type is REDIRECT.
module_tag -- The tag of the module sent from (default None)
Used only when data_type is INIT.
module_name -- The name of the module sent from (default None)
Used only when data_type is INIT.
"""

self.data_type = data_type
self.data = data
self.tag = module_tag
self.name = module_name
self.redirect = redirect_module

# def __str__(self):
# return self.tag

def __lt__(self, other):
"""Just a workaround, might fix someday OωO"""
return True
Loading

0 comments on commit c13604c

Please sign in to comment.