Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Telegram long polling #2250

Merged
merged 20 commits into from
Aug 24, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
#561 handle conflict error with telegram long polling
  • Loading branch information
alexintech committed Jul 11, 2023
commit 5e4cdc7e585478bdf6431cf62b48e61db585342c
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

- Allow mobile app to consume "internal" schedules API endpoints by @joeyorlando ([#2109](https://github.com/grafana/oncall/pull/2109))
- Add inbound email address in integration API by @vadimkerr ([#2113](https://github.com/grafana/oncall/pull/2113))
- Use Telegram polling protocol instead of a webhook if `TELEGRAM_LONG_POLLING_ENABLED` set to `True` by @alexintech

### Changed

Expand Down
5 changes: 1 addition & 4 deletions engine/apps/api/views/live_setting.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from apps.oss_installation.tasks import sync_users_with_cloud
from apps.slack.tasks import unpopulate_slack_user_identities
from apps.telegram.client import TelegramClient
from apps.telegram.tasks import register_telegram_webhook, start_telegram_polling
from apps.telegram.tasks import register_telegram_webhook
from apps.user_management.models import User
from common.api_helpers.mixins import PublicPrimaryKeyMixin

Expand Down Expand Up @@ -66,9 +66,6 @@ def perform_destroy(self, instance):
self._post_update_hook(name, old_value)

def _post_update_hook(self, name, old_value):
if name == "TELEGRAM_LONG_POLLING_ENABLED":
start_telegram_polling.delay()

if name == "TELEGRAM_TOKEN":
self._reset_telegram_integration(old_token=old_value)
register_telegram_webhook.delay()
Expand Down
2 changes: 0 additions & 2 deletions engine/apps/base/models/live_setting.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ class LiveSetting(models.Model):
"TWILIO_VERIFY_SERVICE_SID",
"TELEGRAM_TOKEN",
"TELEGRAM_WEBHOOK_HOST",
"TELEGRAM_LONG_POLLING_ENABLED",
"SLACK_CLIENT_OAUTH_ID",
"SLACK_CLIENT_OAUTH_SECRET",
"SLACK_SIGNING_SECRET",
Expand Down Expand Up @@ -148,7 +147,6 @@ class LiveSetting(models.Model):
"TELEGRAM_WEBHOOK_HOST": (
"Externally available URL for Telegram to make requests. Must use https and ports 80, 88, 443, 8443."
),
"TELEGRAM_LONG_POLLING_ENABLED": ("Enable Telegram long polling instead of webhook integration."),
"SEND_ANONYMOUS_USAGE_STATS": (
"Grafana OnCall will send anonymous, but uniquely-identifiable usage analytics to Grafana Labs."
" These statistics are sent to https://stats.grafana.org/. For more information on what's sent, look at the "
Expand Down
4 changes: 4 additions & 0 deletions engine/apps/base/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import phonenumbers
from django.apps import apps
from django.conf import settings
from phonenumbers import NumberParseException
from telegram import Bot
from twilio.base.exceptions import TwilioException
Expand Down Expand Up @@ -136,6 +137,9 @@ def _check_telegram_token(cls, telegram_token):

@classmethod
def _check_telegram_webhook_host(cls, telegram_webhook_host):
if settings.TELEGRAM_LONG_POLLING_ENABLED:
return

try:
# avoid circular import
from apps.telegram.client import TelegramClient
Expand Down
16 changes: 16 additions & 0 deletions engine/apps/telegram/tasks.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import logging

import telegram.error
from celery import uuid as celery_uuid
from celery.utils.log import get_task_logger
from django.apps import apps
Expand Down Expand Up @@ -30,6 +31,9 @@
)
@handle_missing_token
def register_telegram_webhook(token=None):
if settings.TELEGRAM_LONG_POLLING_ENABLED:
return

telegram_client = TelegramClient(token=token)

try:
Expand All @@ -48,6 +52,10 @@ def start_telegram_polling(token=None):
telegram_client.delete_webhook()

updater = Updater(token=telegram_client.token, use_context=True)

# Register the error handler function with the dispatcher
updater.dispatcher.add_error_handler(error_handler)

callback_handler = CallbackQueryHandler(handle_message)

# register the message handler function with the dispatcher
Expand All @@ -58,6 +66,14 @@ def start_telegram_polling(token=None):
updater.start_polling()


def error_handler(update, context):
try:
raise context.error
except telegram.error.Conflict as e:
# Handle conflict error here
logger.warning(f"Tried to start telegram long polling, but conflict exists, got error: {e}")


def handle_message(update, context):
logger.info(f"Update from Telegram: {update}")
from apps.telegram.updates.update_manager import UpdateManager
Expand Down
7 changes: 5 additions & 2 deletions engine/engine/celery.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,12 @@ def on_after_setup_logger(logger, **kwargs):

@celery.signals.worker_ready.connect
def on_worker_ready(*args, **kwargs):
from apps.telegram.tasks import register_telegram_webhook
from apps.telegram.tasks import register_telegram_webhook, start_telegram_polling

register_telegram_webhook.delay()
if settings.TELEGRAM_LONG_POLLING_ENABLED:
start_telegram_polling.delay()
else:
register_telegram_webhook.delay()


if settings.OTEL_TRACING_ENABLED and settings.OTEL_EXPORTER_OTLP_ENDPOINT:
Expand Down