Skip to content

Instantly share code, notes, and snippets.

@sevazhidkov
Created August 10, 2017 18:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sevazhidkov/b316d48f6d967673fabe22f6071833cc to your computer and use it in GitHub Desktop.
Save sevazhidkov/b316d48f6d967673fabe22f6071833cc to your computer and use it in GitHub Desktop.
VK Anonymous Chat Bot
import vk_api
import requests
import telegram
from telegram.error import NetworkError, Unauthorized
from time import sleep
vk_session = vk_api.VkApi('***', '***')
vk_session.auth()
vk = vk_session.get_api()
upload = vk_api.VkUpload(vk_session)
update_id = None
chat_id = 3
def main():
global update_id
# Telegram Bot Authorization Token
bot = telegram.Bot('***')
# get the first pending update_id, this is so we can skip over it in case
# we get an "Unauthorized" exception.
try:
update_id = bot.get_updates()[0].update_id
except IndexError:
update_id = None
while True:
try:
echo(bot)
except NetworkError:
sleep(1)
except Unauthorized:
# The user has removed or blocked the bot.
update_id += 1
except Exception as e:
print(e)
update_id += 1
def echo(bot):
global update_id
# Request updates after the last update_id
for update in bot.get_updates(offset=update_id, timeout=10):
update_id = update.update_id + 1
if update.message: # your bot can receive updates without messages
# Reply to the message
update.message.reply_text('OK.')
message = update.message
if message.text and message.text != '/start':
vk.messages.send(chat_id=chat_id, message=message.text)
if message.photo:
file_id = message.photo[-1].file_id
photo_file = bot.get_file(file_id)
f_name = '/tmp/{}.jpg'.format(file_id)
photo_file.download(f_name)
uploaded_photos = upload.photo_messages(f_name)
photo = uploaded_photos[0]
vk.messages.send(
chat_id=chat_id,
attachment='photo{}_{}'.format(photo['owner_id'], photo['id'])
)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment