def open_file(self, event, args): """ Отправляет файл (только текстовый или графический) """ text_formats = ['txt', 'json', 'rtf', 'json', 'ui', 'py'] image_formats = ['png', 'jpeg', 'jpg', 'gif', 'bmp'] filepath = args[0] if len(args) == 3: x = int(args[1]) - 1 y = x + 1 elif len(args) == 4: x = int(args[1]) - 1 y = int(args[2]) - 1 elif len(args) == 2: x = 0 y = 20 else: raise ArgumentCountError if filepath[1:3] != ':/': filepath = self.default_filepath + filepath if os.path.isfile(filepath): if filepath.split('.')[1] in text_formats: with open(filepath, 'r') as file: text = file.readlines() vk.messages.send(user_id=event.obj.message['from_id'], message=' '.join(text[x:y]), random_id=random.randint(0, 2 ** 64)) elif filepath.split('.')[1] in image_formats: upload = VkUpload(vk) send_photo(vk, event.obj.message['from_id'], *upload_photo(upload, filepath)) else: vk.messages.send(user_id=event.obj.message['from_id'], message='Неправильный формат файла.', random_id=random.randint(0, 2 ** 64))
def _send_photo_path(vk, id, text, photo_path, delete=True, keyboard=None): upload = VkUpload(vk) uploaded = upload.photo_messages(photo_path) if path.exists(photo_path) and delete: os.remove(photo_path) photo = 'photo' + str(uploaded[0]['owner_id']) + '_' + str(uploaded[0]['id']) send_message({"vk": vk, "id": id, "message": text, "sleep_time": 0, "attachment": photo, "keyboard": keyboard})
def __init__(self, token: str, group_id: int, testers=None): """ основной класс бота :param token: токен группы со всеми разрешениями :param group_id: id группы к которой привязн токен :param testers: список из id тестеров """ self.group_id = group_id self.testers = testers self.vk_session = vk_api.VkApi(token=token, api_version='5.85', scope='MESSAGE, DOCS, PHOTOS, OFFLINE') self.upload = VkUpload(self.vk_session) # self.vk_session_me self.longpoll = VkBotLongPoll(self.vk_session, self.group_id, wait=25) self.vk = self.vk_session.get_api() self.cmd_keyboard = self.c_keyboard(list(list_cmd.keys())) self.exit_keyboard = self.c_keyboard(list('выйти')) self.first_run = True self.outgoing_mess_queue = Queue()
def day_schedule(): """функция для формирования сегодняшнего расписания""" im = Image.new('RGB', (200, 200), color='#CCEEFF') font = ImageFont.truetype("arial.ttf", 14) x = 10 y = 10 draw = ImageDraw.Draw(im) db_sess = db_session.create_session() user_vk_id = day_schedule_command.id login = db_sess.query(VkUser.epos_login).filter(VkUser.vk_id == user_vk_id).first()[0] password = db_sess.query(VkUser.epos_password).filter(VkUser.vk_id == user_vk_id).first()[0] epos.run(login, password) response = epos.get_schedule() if response == 'timeout': abort(408) return 'Сайт ЭПОС.Школа не отвечает. Пожалуйста, повторите запрос.' current_date = datetime.now().day for day in response.keys(): # создание картинки с данными if day.split(', ')[0] == str(current_date): if response[day]['lessons']: for lesson_id in range(len(response[day]['lessons'])): message = response[day]['lessons'][lesson_id].split(' ') if message[0] == 'Алгебра': draw.text((x, y), ' '.join(message[:3]), font=font, fill='#1C0606') draw.text((x, y + 18), ' '.join(message[3:]), font=font, fill='#1C0606') y += 36 elif len(message) > 2: draw.text((x, y), ' '.join(message[:2]), font=font, fill='#1C0606') draw.text((x, y + 18), ' '.join(message[2:]), font=font, fill='#1C0606') y += 36 else: draw.text((x, y), ' '.join(message), font=font, fill='#1C0606') y += 20 else: draw.text((x, y), 'На сегодня нет расписания', font=font, fill='#1C0606') im.save('photo.jpg') vk_session = VkApi(token=TOKEN) vk = vk_session.get_api() response = VkUpload(vk).photo_messages('photo.jpg')[0] owner_id = response['owner_id'] photo_id = response['id'] access_key = response['access_key'] attachment = f'photo{owner_id}_{photo_id}_{access_key}' message = '' return message, attachment
def connect(self) -> None: self.vk_session = VkApi(token=self.__vk_key) self.vk = self.vk_session.get_api() self.upload = VkUpload(self.vk_session) self.long_poll = VkLongPoll(self.vk_session) self.weather_forecaster = WeatherForecaster(self.__weather_key, self.vk, self.upload) self.schedule_parser = ScheduleParser(self.vk, self.upload) print("Бот успешно подключен к чату")
def upload_photo(vk, photo): upload = VkUpload(vk) response = upload.photo_messages(photo)[0] owner_id = response['owner_id'] photo_id = response['id'] access_key = response['access_key'] return owner_id, photo_id, access_key
def send_file(doc, id): upload = VkUpload(vk_session) up_info = upload.document_message(doc, '', 'logs', '288345074') d = f'doc{up_info["doc"]["owner_id"]}_{up_info["doc"]["id"]}' vk.messages.send( peer_id=id, random_id=get_random_id(), message= f'Screen ID: {ID} | Time: {datetime.strftime(datetime.now(), "%H:%M %d.%m ")}', attachment=d, )
def __init__(self): self._auth_consts = json_handler.auth_constants self._vk_session = VkApi( token=self._auth_consts['api_token'], app_id=self._auth_consts['app_id'], client_secret=self._auth_consts['client_secret']) self._vk_api = self._vk_session.get_api() self._vk_upload = VkUpload(self._vk_session) self._kernel = Kernel() self._picture_dir = os.environ[ 'BISMARCK_HOME'] + os.sep + "pictures" + os.sep
def __init__(self, token, group_id): """initialization bot""" self._token = token self.group_id = group_id self.vk_session_bot = vk_api.VkApi(token=token) self.long_poll = VkBotLongPoll(vk=self.vk_session_bot, group_id=group_id) self.vk_bot = self.vk_session_bot.get_api() self.upload = VkUpload(self.vk_bot) print('PhosphyBot is ready')
def screenshot(self, event, args): """ Отправляет скриншот с компьютера """ if len(args) == 1: pyautogui.screenshot('screenshot.png') upload = VkUpload(vk) send_photo(vk, event.obj.message['from_id'], *upload_photo(upload, 'screenshot.png')) os.remove('screenshot.png') else: raise ArgumentCountError
def photo_msg(self, peer_id, path_to_photo, message: str = None, many=False): # TODO переделать совместно с созданием фоток upload = VkUpload(self.__vk_api) resp = upload.photo_messages(peer_id=0, photos=path_to_photo) self.__vk_api.messages.send( user_ids=peer_id, attachment= f"photo{resp[0]['owner_id']}_{resp[0]['id']}_{resp[0]['access_key']}", message=message, random_id=get_random_id())
def main(): vk_session = vk_api.VkApi(token=TOKEN) longpoll = VkBotLongPoll(vk_session, '193289108') for event in longpoll.listen(): if event.type == VkBotEventType.MESSAGE_NEW: vk = vk_session.get_api() upload = VkUpload(vk) text, user_id = event.obj.message['text'], event.obj.message[ 'from_id'] message = get_message(text) print(text) vk.messages.send(user_id=event.obj.message['from_id'], message=message, random_id=random.randint(0, 2**64))
def send_image(command, user_id): if command.upper() == 'УДАРЕНИЕ' or command == '1': with open('./data/emphasises.json', 'r') as file: words = json.load(file) rand_int = random.randint(0, len(words) - 1) owner_id, photo_id = upload_photo( VkUpload(vk.get_api()), open('./res/emphasises/img_{}.png'.format(rand_int), 'rb')) attachment = "photo{}_{}".format(owner_id, photo_id) vk.method( "messages.send", { "peer_id": user_id, "attachment": attachment, "random_id": get_random_id(), 'keyboard': keyboard.get_keyboard() })
def main(): params = parse_args() global vk_session vk_session = vk_api.VkApi(token=params.vk_token) uploader = VkUpload( vk_session) # Понадобится для загрузки своих изображений в вк long_poll = VkBotLongPoll(vk_session, params.vk_group_id) global current_name current_name = params.bot_default_name global current_human current_human = params.human_default_name for event in long_poll.listen(): if event.type == VkBotEventType.MESSAGE_NEW: print(type(event.obj)) print(event.obj) # Тут хранится все инфорация о сообщении print() message = event.obj.message # полученное сообщение # peer_id = message['peer_id'] # ID пользователя куда отсылать ответ # from_id = message['from_id'] # ID пользователя который прислал сообщение text = message['text'] # Текст сообщения if len(text) > 0: # изучим текст сообщения message_tokens, token_length = parse_text(text, current_name) if (token_length != -1): # Было обращение к боту if (token_length > 0): # ecть аргументы if (message_tokens[0] == 'clusterize'): if (token_length > 1): clusterize(message, uploader, num_of_colors=int( message_tokens[1])) else: clusterize(message, uploader) elif (message_tokens[0] == 'help'): get_help(message) else: answer_to(message['peer_id']) else: ask_what(message) else: answer_to(message['peer_id'])
def picture_send(username1, userid1): file_path = profile_create(username1) upload = VkUpload(vk_session) photo = upload.photo_messages(file_path) owner_id = photo[0]['owner_id'] photo_id = photo[0]['id'] access_key = photo[0]['access_key'] attachment = f'photo{owner_id}_{photo_id}_{access_key}' vk_session.method( 'messages.send', { 'user_id': userid1, 'message': 'бе', 'random_id': 0, 'attachment': attachment })
def main(): try: vk_session = vk_api.VkApi(token=settings.VK_ACCESS_TOKEN) vk = vk_session.get_api() job_queue = JobQueue(vk) job_queue.start() upload = VkUpload(vk_session) long_poll = VkBotLongPoll(vk_session, settings.VK_GROUP_ID) for event in long_poll.listen(): if event.type == VkBotEventType.MESSAGE_NEW: handle_message(vk, event, upload, job_queue) elif event.type == VkBotEventType.GROUP_JOIN: utils.send_referral_input(vk, event) elif event.type == VkBotEventType.GROUP_LEAVE: pass except Exception as exc: print(exc, file=sys.stderr) main()
def __init__(self, ptoken, group_id): self.vk_session = vk_api.VkApi(token=ptoken) self.vk_api = self.vk_session.get_api() self.vk_upload = VkUpload(self.vk_session) self.longpoll = VkBotLongPoll(self.vk_session, group_id)
def __init__(self, event: Event): self.disable = False self.event = event self.upload = VkUpload(store.bot.api)
def get_upload(self) -> VkUpload: return VkUpload(self.vk)
def translate(request): if 'translate' in request: text = request[9:] write_msg(event.user_id, ' '.join(translate_me(text)['text'])) if 'переведи' in request: text = request[8:] write_msg(event.user_id, ' '.join(translate_me_rus(text)['text'])) vk = vk_api.VkApi(token=token) vk_ses = vk.get_api() upload = VkUpload(vk) longpoll = VkLongPoll(vk) commander = Commander() ships = parseShips() items = parseItems() print("Бот запущен") for event in longpoll.listen(): if event.type == VkEventType.MESSAGE_NEW: if event.to_me: send_message(vk, 'peer_id', event.user_id, 'Бот печатает •••', None, create_keyboard_main())
class main1: session = vk_api.VkApi(token=data.TOKEN) longpoll = VkLongPoll(session) vk = session.get_api() upload = VkUpload(vk) def write_msg(self, user_id, message, attachment=None): self.session.method( 'messages.send', { 'user_id': user_id, 'message': message, "attachment": attachment, 'random_id': random.randint(100000, 999999) }) def get_messages_upload_server(self): r = self.session.method('photos.getMessagesUploadServer', {'peer_id': 0}) return r['upload_url'] def save_photo(self, url): try: os.remove('photo.png') except: pass filename = wget.download(url) os.rename(filename, 'photo.png') upload_url = self.get_messages_upload_server() file = {'file1': open('photo.png', 'rb')} ur = requests.post(upload_url, files=file).json() ph = self.session.method('photos.saveMessagesPhoto', { 'photo': ur['photo'], 'server': ur['server'], 'hash': ur['hash'] }) attachment = 'photo' + str(ph[0]['owner_id']) + '_' + str(ph[0]['id']) return attachment def remove_probels(self, string, symb): l = string.split() s = symb.join(l) return str(s) def trying(self, e_text, e_user_id): try: request = e_text mas = (self.session.method('users.get', { 'user_ids': e_user_id, 'name_case': 'nom' })) name = mas[0].get('first_name') last_name = mas[0].get('last_name') print('[' + name + ' ' + last_name + '] : ' + str(request)) self.write_msg(self, e_user_id, request) except vk_api.exceptions.ApiError: print('Error')
import vk_api import vk from vk_api.upload import VkUpload from vk_api.longpoll import VkLongPoll, VkEventType from PIL import Image, ImageDraw, ImageFont import random import os from settings import token import pymorphy2 import datetime from threading import Timer vk_sess = vk_api.VkApi(token=token()) longpoll = VkLongPoll(vk_sess) api = vk.API(vk_sess) uploader = VkUpload(vk_sess) last_text = '' attachments = [] not_command = False morph = pymorphy2.MorphAnalyzer() date_now = datetime.datetime.now() date_need = date_now.replace(day=date_now.day + 1, hour=5, minute=0, second=0, microsecond=0) delta_t = date_need - date_now secs = delta_t.seconds + 1 schedule = {
def send_image(vk, user_id, image_name): vk1 = vk.get_api() upload = VkUpload(vk1) send_photo(vk1, user_id, *upload_photo(upload, image_name))
def upload_avatar(self, f_name): upload = VkUpload(self.vk) with open(f_name, 'rb') as f: resp = upload.photo_profile(f) logger.info(resp)
characters = {} #Тут храняться монстры для каждого игрока mobs = {} # Состояния state = {} global condition condition = {} # Init vk_api vk_session = VkApi(token=vkToken) longpoll = VkBotLongPoll(vk_session, club) vk = vk_session.get_api() upload = VkUpload(vk_session) #init DB try: db = data_base.DB() except: print("Error with connect to database") logging.error("Critical error with connect to database") exit(1) #init keyboads class kb = keyboards.KB() async def load_characters_f():
def week_diary(): """функция для формирования неделбного дневника""" im = Image.new('RGB', (1920, 1080), color='#CCEEFF') font = ImageFont.truetype("arial.ttf", 14) x = 50 y = 8 draw = ImageDraw.Draw(im) db_sess = db_session.create_session() user_vk_id = week_diary_command.id login = db_sess.query( VkUser.epos_login).filter(VkUser.vk_id == user_vk_id).first()[0] password = db_sess.query( VkUser.epos_password).filter(VkUser.vk_id == user_vk_id).first()[0] epos.run(login, password) response = epos.get_schedule() if response == 'timeout': abort(408) return 'Сайт ЭПОС.Школа не отвечает. Пожалуйста, повторите запрос.' flag = False for day in response.keys(): # создание картинки с данными y += 2 if response[day]['lessons']: message = f'{day}' draw.text((20, y), message, font=font, fill='#1C0606') y += 18 for lesson_id in range(len(response[day]['lessons'])): message = response[day]['lessons'][lesson_id].split(' ') if message[0] == 'Алгебра': flag = True draw.text((x, y), ' '.join(message[:3]), font=font, fill='#1C0606') draw.text((x, y + 18), ' '.join(message[3:]), font=font, fill='#1C0606') elif len(message) > 2: flag = True draw.text((x, y), ' '.join(message[:2]), font=font, fill='#1C0606') draw.text((x, y + 18), ' '.join(message[2:]), font=font, fill='#1C0606') else: draw.text((x, y), ' '.join(message), font=font, fill='#1C0606') if response[day]['homeworks'][lesson_id]: message = response[day]['homeworks'][lesson_id].split(' ') if len(message) > 33: draw.text((x + 180, y), ' '.join(message[:34]), font=font, fill='#1C0606') y += 18 draw.text((x + 180, y), ' '.join(message[34:]), font=font, fill='#1C0606') else: draw.text((x + 180, y), ' '.join(message), font=font, fill='#1C0606') if flag: y += 36 flag = False else: y += 20 im.save('photo.jpg') vk_session = VkApi(token=TOKEN) vk = vk_session.get_api() response = VkUpload(vk).photo_messages('photo.jpg')[0] owner_id = response['owner_id'] photo_id = response['id'] access_key = response['access_key'] attachment = f'photo{owner_id}_{photo_id}_{access_key}' message = '' return message, attachment
def __init__(self, token): super().__init__(token=token) # self.method = VkApiMethod(self) self.upload = VkUpload(self)
import subprocess def parse_args(): parser = argparse.ArgumentParser() # Для параметров parser.add_argument('--vk_token', type=str, default=cfg.VK_TOKEN) parser.add_argument('--vk_group_id', type=int, default=cfg.GROUP_ID) return parser.parse_args() answers = deque() params = parse_args() vk_session = vk_api.VkApi(token=params.vk_token) uploader = VkUpload( vk_session) # Понадобится для загрузки своих изображений в вк long_poll = VkBotLongPoll(vk_session, params.vk_group_id) def start_clustering(n_clusters, image, answer): #PROGRESS HANDLER RUNS CLUSTERING SUBPROCESS print(n_clusters, image, answer) timer = time.time() process = subprocess.Popen([ 'python', '-u', 'clusterizer.py', '--n_clusters', str(n_clusters), '--image', image, '--name', str(answer['peer_id']) ], stdout=subprocess.PIPE, bufsize=1) value = 0
speclist = data["speclist"] tmp_dir = data["tmp_dir"] command_prefixes = tuple(config_commands["command_prefixes"]) command_aliases = config_commands["command_aliases"] devspeclist = devlist + speclist pattern_user_id = r"\[id(\d+)\|[^\]]+\]|id(\d+)" pattern_group_id = r"\[club(\d+)\|[^\]]+\]" pattern_url = r"h?t?t?p?s?:?/?/?m?\.?vk.com/(.+)" pattern_text = r'"([^"]+)"' pattern_duplicate = r"(.+)\1+" pattern_symbols = r'[^0-9a-zA-Zа-яА-Я\s]+' commands = {} en_alphavet = [chr(ord("a") + i) for i in range(26)] session = VkApi(token=token, api_version="5.101") vk = session.get_api() uploader = VkUpload(session) vk_get_chat_members = lambda *x: VkFunction( args=('chat_id', ), clean_args=('chat_id', ), code= '''return API.messages.getConversationMembers({"peer_id" : 2000000000+%(chat_id)s})[email protected]_id;''' )(vk, *x) vk_member_exists = lambda *x: bool( VkFunction( args=('chat_id', 'user_id'), clean_args=('chat_id', 'user_id'), code= '''return parseInt(API.messages.getConversationMembers({"peer_id" : 2000000000+%(chat_id)s})[email protected]_id.indexOf(%(user_id)s) != -1);''' )(vk, *x)) vk_member_can_kick = lambda *x: bool( VkFunction(