Example #1
0
def telegram_hook(request):
    update = json.loads(request.body)
    message = update.get('message')
    text = None

    if message is None:
        return HttpResponse('OK')

    user_id = message['from']['id']

    if 'voice' in message.keys():
        file_id = message['voice']['file_id']
        file_path = get_telegram_file_path(file_id)
        voice_message = download_file(file_path)
        file_src = write_audio_file(voice_message, user_id)
        convert_audio_file(file_src, user_id)
        text = 'Your voice message saved'

    elif 'photo' in message.keys():
        file_id = message['photo'][-1]['file_id']
        file_path = get_telegram_file_path(file_id)
        img = download_file(file_path)
        count_faces = found_faces_on_image(img)
        if count_faces > 0:
            save_image(img, user_id)
            text = f'Found {count_faces} faces' if count_faces > 1 else f'Found {count_faces} face'
        else:
            text = 'Face not found '

    invoke_telegram('sendMessage',
                    chat_id=update['message']['chat']['id'],
                    text=text)

    return HttpResponse('OK')
Example #2
0
def telegram_emotion(message):
    c = message['chat']['id']
    if 'sad' in message['text']:
        update = json.loads(requests.post('http://muzis.ru/api/search.api?q_value=25201?value=5'))
        message = update['message']
        invoke_telegram('sendVoice', audio=message['songs']['file_mp3'], chat_id=c)
    elif 'happy' in message['text']:
        update = json.loads(requests.post('http://muzis.ru/api/search.api?q_value=25739?value=5'))
        message = update['message']
        invoke_telegram('sendVoice', audio=message['songs']['file_mp3'], chat_id=c)
Example #3
0
def _send_telegram_by_username(username, text):
    lst = TelegramChat.objects.filter(username=username)
    if len(lst) == 0:
        raise Exception("Could not find chat by username %s" % username)

    for c in lst:
        resp = invoke_telegram('sendMessage', text=text.encode('utf-8'), chat_id=c.chat_id)
Example #4
0
def start_ping_site(site_url):
    resp = requests.get(site_url)
    status_code = resp.status_code
    if status_code != 200:
        try:
            site = Site.objects.get(site_url=site_url)
        except:
            return 'error site in database'

        site_chat_objs = SiteChat.objects.filter(site_id=site)
        for site_chat in site_chat_objs:
            invoke_telegram(
                'sendMessage',
                text=f'Error code {status_code} for site {site_url}',
                chat_id=site_chat.chat_id_id)
    return f'{site_url} - {status_code}'
Example #5
0
def telegram_hook(request):
    update = json.loads(request.body)
    if 'message' not in update:
        return HttpResponse('OK')
    message = update['message']

    text = ''
    if 'text' in message:
        text = message['text']

    if '/start' in text:
        invoke_telegram('sendMessage', chat_id=update['message']['chat']['id'], text='Hello world')
    elif '/getprice' in text:
        current_price = get_cur_price_btc()
        invoke_telegram('sendMessage', chat_id=update['message']['chat']['id'], text=current_price)

    return HttpResponse('OK')
Example #6
0
def telegram_commands(message, request):
    commands = {'help','start','song','set'}
    if message['text'][1:] not in commands:
        resp = invoke_telegram('sendMessage', text='Command does not exist', chat_id=message['chat']['id'])
    elif message['text'][1:] == 'song':
        _send_telegram_by_username(message['chat']['username'],'Name the song')
        c = message['chat']['id']
        update = json.loads(request.body)
        message = update['message']
        update = json.loads(requests.post('http://muzis.ru/api/search.api?q_track',data= message['text']))
        message = update['message']
        invoke_telegram('sendVoice', audio=message['songs']['file_mp3'],chat_id=c)
    elif message['text'][1:] == 'sim':
        _send_telegram_by_username(message['chat']['username'], 'For what songs you want get suggsetions?')
        c = message['chat']['id']
        update = json.loads(request.body)
        message = update['message']
        update = json.loads(requests.post('http://muzis.ru//api/similar_performers.api?performer_id?value=5', data=message['text']))
        message = update['message']
        for x in message['songs']['songs']:
            invoke_telegram('sendVoice', audio=x, chat_id=c)
    elif message['text'][1:] == 'genre':
        genre = message['text'].split()[-1]
        _send_telegram_by_username(message['chat']['username'], 'Good choice')
        c = message['chat']['id']
        update = json.loads(request.body)
        message = update['message']
        update = json.loads(requests.post('http://muzis.ru/api/stream_from_values.api?values?value=5', data=message['text']))
        message = update['message']
        for x in message['songs']['songs']:
            invoke_telegram('sendVoice', audio=x, chat_id=c)
Example #7
0
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, re_path
from ping_bot.settings import ENDPOINT_URL
from django_celery_beat.models import PeriodicTask, IntervalSchedule

from core.telegram_api import invoke_telegram
from core.views import telegram_hook

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^api/telegram_hook/?', telegram_hook, name='telegram_hook'),
]

# Назначаем адрес для хуков телеграма
invoke_telegram('setWebhook', url=f'{ENDPOINT_URL}/api/telegram_hook/')

PeriodicTask.objects.all().delete()
IntervalSchedule.objects.all().delete()

from core.models import *
Chat.objects.all().delete()
Site.objects.all().delete()
SiteChat.objects.all().delete()
Example #8
0
def telegram_hook(request):
    update = json.loads(request.body)
    message = update.get('message')
    text = None

    if message is None:
        return HttpResponse('OK')

    text = message.get('text')

    if text is None:
        return HttpResponse('OK')

    command = text.split()[0]

    if command == '/user_graph' or command == '/group_graph':
        try:
            vk_id = int(text.split()[1])
            if command == '/user_graph':
                with open('store/1.jpg', 'rb') as f:
                    photo = f.read()
                invoke_telegram('sendPhoto',
                                photo=photo,
                                chat_id=update['message']['chat']['id'])

                Logging.objects.create(user_id=update['message']['chat']['id'],
                                       command='user_graph')
            elif command == '/group_graph':

                from core.tasks import test
                test.delay(update['message']['chat']['id'])

                invoke_telegram('sendMessage',
                                chat_id=update['message']['chat']['id'],
                                text=f'id группы {vk_id}')
                Logging.objects.create(user_id=update['message']['chat']['id'],
                                       command='group_graph')

        except IndexError:
            invoke_telegram('sendMessage',
                            chat_id=update['message']['chat']['id'],
                            text='Вы не ввели id')
        except ValueError:
            invoke_telegram('sendMessage',
                            chat_id=update['message']['chat']['id'],
                            text='id должен быть целым числом')

    elif command == '/stats':
        try:
            admin = Admin.objects.get(
                tg_id=int(update['message']['chat']['id']))
            users = len(Logging.objects.all())
            unic_users = len(
                Logging.objects.order_by().values_list('user_id').distinct())

            invoke_telegram(
                'sendMessage',
                chat_id=update['message']['chat']['id'],
                text=
                f'Уникальных пользователей: {unic_users}\n Всего пользователей: {users}'
            )

        except:
            invoke_telegram('sendMessage',
                            chat_id=update['message']['chat']['id'],
                            text=f'Нет прав')

    elif command == '/add_admin' and settings.ADMIN_ID == int(
            update['message']['chat']['id']):
        tg_id = int(text.split()[1])
        Admin.objects.create(tg_id=tg_id)
    elif command == '/delete_admin' and settings.ADMIN_ID == int(
            update['message']['chat']['id']):
        tg_id = int(text.split()[1])
        Admin.objects.get(tg_id=tg_id).delete()

    return HttpResponse('OK')
Example #9
0
def init(request):
    invoke_telegram('setWebhook', url=settings.TELEGRAM_HOOK_URL)

    return HttpResponse('OK')
Example #10
0
"""asl URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from core.telegram_api import invoke_telegram
from django.conf.urls import url
from django.contrib import admin
from core import views
from asl import settings

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^telegram_hook/?', views.telegram_hook, name='telegram_hook')
]



invoke_telegram('setWebhook', url=settings.TELEGRAM_HOOK_URL)
Example #11
0
"""exchange_rate_bot URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, re_path

from core.views import telegram_hook
from core.telegram_api import invoke_telegram

from exchange_rate_bot import settings

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^api/telegram_hook/?', telegram_hook, name='telegram_hook'),
]

invoke_telegram('setWebhook', url=f'https://exchange-bot-btc.herokuapp.com/api/telegram_hook/')
Example #12
0
def get_telegram_file_path(file_id):
    return json.loads(invoke_telegram(
        'getFile', file_id=file_id).content)['result']['file_path']
"""micro URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.conf.urls import url
from django.urls import path
from django.urls import reverse
from core.telegram_api import invoke_telegram
from core import views
from micro import settings

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^api/telegram_hook/?', views.telegram_hook, name='telegram_hook'),
]

invoke_telegram('setWebhook',
                url=f'https://{settings.URL}{reverse(views.telegram_hook)}')