示例#1
0
def longpollserver():
    def get_lp_server():
        lp_info = requests.post(
            'https://api.vk.com/method/groups.getLongPollServer',
            data={
                'access_token': CONFIG['token'],
                'v': '5.80',
                'group_id': CONFIG['group_id']
            })
        if CONFIG['debug']:
            print(lp_info.text)
        lp_info = json.loads(lp_info.text)['response']
        lanode.log_print(
            'Новая информация о longpoll сервере успешно получена', 'info')
        return lp_info

    lp_info = get_lp_server()
    lanode.log_print('Longpoll поток запущен.', 'info')
    while True:
        time.sleep(10 / 1000000.0)
        lp_url = lp_info['server'] + '?act=a_check&key=' + lp_info['key'] + '&ts=' + \
                 str(lp_info['ts']) + '&wait=60'
        result = json.loads(requests.get(lp_url).text)
        try:
            lp_info['ts'] = result['ts']
            for update in result['updates']:
                updates_queue.put(update)
        except KeyError:
            lp_info = get_lp_server()
示例#2
0
 def get_lp_server():
     lp_info = requests.post(
         'https://api.vk.com/method/groups.getLongPollServer',
         data={
             'access_token': CONFIG['token'],
             'v': '5.80',
             'group_id': CONFIG['group_id']
         })
     if CONFIG['debug']:
         print(lp_info.text)
     lp_info = json.loads(lp_info.text)['response']
     lanode.log_print(
         'Новая информация о longpoll сервере успешно получена', 'info')
     return lp_info
示例#3
0
def start():
    lanode.log_print('Инициализация скриптов...', 'info')
    # for script in filter(lambda x: x.split('.')[-1] == 'py', os.listdir('./scripts')):
    #     exec(open('./scripts/' + script).read())
    for script in [
            x for x in os.listdir('./scripts/')
            if (not os.path.isdir('./scripts/' + x)) and (x[-3:] == '.py')
    ]:
        spec = importlib.util.spec_from_file_location(
            script.split('.')[0], './scripts/' + script)
        module = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(module)
        scripts.scripts_list[script[:-3]] = module

    contexts.context_list = {
        x.__name__: {
            'class': x,
            'copies': {
                0: x(0)
            }
        }
        for x in contexts.BaseContext.__subclasses__()
    }

    for f in events.get_events('on_load'):
        f()

    if CONFIG['debug'] is True:
        print(os.path.dirname(__file__))
        print(scripts.scripts_list)
        print(contexts.context_list)

    lanode.log_print('Инициализация скриптов завершена.', 'info')

    lanode.log_print('Запуск longpoll потока ...', 'info')
    thread_longpoll = threading.Thread(target=longpollserver)
    thread_longpoll.start()

    hour_timer = datetime.now().hour
    while True:
        time.sleep(10 / 1000000.0)

        if datetime.now().hour > hour_timer:
            counters['msg_recv']['hour'] = 0
            counters['msg_send']['hour'] = 0
            counters['msg_recv']['hour_peer'] = {}
            counters['msg_send']['hour_peer'] = {}

        for f in events.get_events('on_evloopiter'):
            f()

        for t in events.get_events('on_timer').copy():
            if t[3] >= time.time():
                if t[1]:
                    t[0](t)
                    events.get_events('on_timer').remove(t)
                else:
                    t[0](t)
                    t[2] = time.time()

                # timers = events.get_events('on_timer').copy()
        # i = 0
        # while i <= len(timers):
        #     t = timers[i]
        #     if t[0]:
        #         t[3]()
        #         events.get_events('on_timer').remove(t)
        #     else:
        #         t[3]()
        #         t[1] =
        #     i += 1

        if not updates_queue.empty():
            update = updates_queue.get()
            if CONFIG['debug'] is True:
                print(update)

            if update['type'] == 'message_new':
                msg = update['object']

                counters['msg_recv']['all'] += 1
                counters['msg_recv']['hour'] += 1
                if msg['peer_id'] in counters['msg_recv']['hour_peer']:
                    counters['msg_recv']['hour_peer'][msg['peer_id']] += 1
                else:
                    counters['msg_recv']['hour_peer'][msg['peer_id']] = 0

                if (msg['peer_id'] > 0) and (msg['peer_id'] < 2000000000):
                    chat_type = 'private'
                elif msg['peer_id'] > 2000000000:
                    chat_type = 'dialog'
                elif msg['peer_id'] < 0:
                    chat_type = 'group_private'

                msg['chat_type'] = chat_type
                if 'text' in msg:
                    msg['text'] = html.unescape(msg['text'])
                else:
                    msg['text'] = ''

                if msg['text'].split(' ')[0] in CONFIG['prefixes']:
                    msg['pure_text'] = ' '.join(
                        msg['text'].split(' ')[1:]).lower()
                elif re.search(r'(\[club(\d+)\|\s*\S+\s*\]).*',
                               msg['text']) is not None:
                    match = re.findall(r'(\[club(\d+)\|\s*\S+\s*\]).*',
                                       msg['text'])[0]
                    if int(match[1]) == CONFIG['group_id']:
                        msg['pure_text'] = msg['text'].replace(
                            match[0] + ' ', '')
                    else:
                        if msg['chat_type'] == 'private':
                            msg['pure_text'] = msg['text']
                        else:
                            continue
                else:
                    if msg['chat_type'] == 'private':
                        msg['pure_text'] = msg['text']
                    else:
                        continue

                if (msg['pure_text'].split(' ')[0].lower() in ('debug', 'dbg', 'дбг', 'дебаг'))\
                    and (debug_func is not None)\
                    and (msg['from_id'] in CONFIG['admins']):
                    debug_func(msg)
                    continue

                lanode.log_print(
                    '(MsgID: ' + str(msg['id']) + ') Получено. '
                    '{SndTime: ' + datetime.fromtimestamp(
                        msg['date']).strftime('%Y.%m.%d %H:%M:%S') + ','
                    ' Chat: ' + str(msg['peer_id']) + ','
                    ' From: ' + str(msg['from_id']) + ','
                    ' Text: "' + msg['text'].replace('\n', '\\n') + '"}',
                    'info')
                # with db.transaction():
                #     if msg['from_id'] not in db:
                #         db[msg['from_id']] = {'settings': {},
                #                               'save': {'context':'MainContext','inventory':{}}}
                #         for f in events.get_events('on_newuser'):
                #             f(msg['from_id'])

                context = contexts.get_context_by_vkid(msg['from_id'])

                if context is None:
                    lanode.log_print(
                        'ERROR: Контекста не существует. Chat: ' +
                        str(msg['peer_id']) + ' From: ' + str(msg['from_id']),
                        'info')
                    for f in events.get_events('on_contextnotfound'):
                        f(msg, contexts.get_contextid_by_vkid(msg['from_id']))
                    continue

                context.on_rawmessage(update)

                # if not any(re.match(x['tmplt'], msg['pure_text']) for x in self.chat.cmds_list.values()):
                #     self.chat.apisay('Такой команды не существует!', msg['peer_id'], msg['id'])
                #     continue

                for f in events.get_events('on_preparemessage'):
                    msg = f(msg)
                    if msg is False:
                        break
                if msg is False:
                    continue

                if CONFIG['debug'] is True:
                    print(msg)

                if msg['from_id'] in chat.scanning_users:
                    for q in chat.scanning_users[msg['from_id']].values():
                        q.put(msg)
                else:
                    print(id(msg))
                    thread = threading.Thread(target=context.on_message,
                                              args=(msg, ))
                    thread.setName(str(msg['id']))
                    thread.start()
示例#4
0
        except KeyError:
            lp_info = get_lp_server()


def stat():
    print()


try:
    vk_api
except NameError:
    pass
else:
    vk_session = vk_api.VkApi(token=CONFIG['token'])
    vk = vk_session.get_api()
    lanode.log_print('Бибилиотека vk_api успешно загружена.')


class Scripts:
    scripts_list = {}

    # def register_plugin(self, name, obj):
    #     self.plugins_list[name] = obj

    # def unregister_plugin(self, name):
    #     del self.plugins_list[name]


class Events:
    # def execute_event(self, event):
    #     results = []
示例#5
0
import os

abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)
import lanode

lanode.log_print('VKRPG v1.0 by Lanode (from Augmeneco)')
import queue
import json
import requests
import threading
import time
import importlib
import importlib.util
import re
from datetime import datetime
import vkrpg
import html
from io import StringIO
import contextlib
import sys

# class VKRPG:
#     updates_queue = queue.Queue()
#
#     def __init__(self):
#         self.chat = self.Chat()
#         self.contexts = self.Contexts(self)
#         self.plugins = self.Plugins()
#         self.events = self.Events()