I got a problem in writing code for my telegram customer service chat. Apparently, let me confess my little knowledge in the field. Can I get open source code for telegram chatbot which automatically forwards the messages sent to it to a specific id (my-id)? Thank you...I'm badly in need of this.
Install pytelegrambotapi (pip install pytelegrambotapi) and then you'll be able to use somthing like that:
import telebot
token = "hd9ouhs98h928w982982"
your_id = "321321321321"
bot = telebot.TeleBot(token)
#bot.message_handler(content_types=["text"])
def repeat_all_messages(message):
bot.send_message(your_id, message.text)
if __name__ == '__main__':
bot.infinity_polling()
Related
I am trying to send a message with python to discord using requests.. Why doesn't this work? Did I do something wrong?
import requests
id = 935325134879850517
r = requests.post(f'http://discord.com/api/v9/channels/{id}/messages', json={'content':'message'}, headers={'authorization': 'token'})
Consider using Discord webhooks, I had problem with API too, but webhooks works very simple -- without auth.
I was trying to check if a new session has been created using the telethon library.
My first idea was to get the warning message from Telegram (New access: [...]), so when I get that kind of message, I know that another device has connected to my account.
I couldn't get that message, so I tried to get it another way:
chat = client.get_entity(777000) # Telegram chat id
print(chat)
for message in client.iter_messages(chat):
print(message.text)
(This is not the full code.)
The only message I was able to retrieve was the confirmation code, but only with that I can't do anything.
Another idea was to continuously receive the list of active sessions (using GetAuthorizationsRequest()) and, if that list changed, it means that a new device has connected to my account. But is it convenient to continuously send requests to Telegram servers?
I searched everywhere but couldn't find a good solution to my problem.
Any help is appreciated.
With the help of Lonami, I was able to solve my problem.
With client.iter_messages(chat), I could only view messages, while the "message" I was looking for was an UpdateServiceNotification, so I used events.Raw to get all types of updates.
Here is the code:
from telethon.sync import TelegramClient, events
from telethon.tl.types import UpdateServiceNotification
api_id = 123456
api_hash = "42132142c132145ej"
with TelegramClient('anon', api_id, api_hash) as client:
#client.on(events.Raw(func = lambda e: type(e) == UpdateServiceNotification))
async def handler(event):
print("New Login!")
client.run_until_disconnected()
I am new to Microsoft Bot Framework, I am learning it through a youtube video https://youtu.be/ynG6Muox81o and making my bot on python3 on Ubuntu.
The Microsoft Bot Emulator says "sending failed. Retry".
Visual Studio Code shows KeyError: 'HTTP_CONTEXT_TYPE'.
I did everything right, my bot is connected to http://localhost:3978/, and bot emulator is connected to http://localhost:3978/api/messages/.
Many people on stackoverflow who had the same issue faced it due to windows firewall, but mine is ubuntu and i did check if it was enabled but its not.
app.py
from flask import Flask, request, Response
from botbuilder.schema import Activity
from botbuilder.core import BotFrameworkAdapter,BotFrameworkAdapterSettings
import asyncio
from echobot import EchoBot
app = Flask(__name__)
loop = asyncio.get_event_loop()
botadaptersettings=BotFrameworkAdapterSettings("","")
botadapter = BotFrameworkAdapter(botadaptersettings)
ebot = EchoBot()
#POST is the message
#app.route("/api/messages",methods=["POST"])
def messages():
#checking if HTTP file format is JSON or not
if "application/json" in request.headers["context-type"]:
#reading the JSON message
jsonmessage = request.json
else:
#unsupported media type 415
return Response(status=415)
activity = Activity().deserialize(jsonmessage)
async def turn_call(turn_context):
await ebot.on_turn(turn_context)
task = loop.create_task(botadapter.process_activity(activity,"",turn_call))
loop.run_until_complete(task)
if __name__ == '__main__':
app.run('localhost',3978)
echobot.py
from botbuilder.core import TurnContext
class EchoBot:
async def on_turn(self,turn_context:TurnContext):
await turn_context.send_activity(turn_context.activity.text)
I cant seem to understand the issue and how to fix it. it would be really helpfull if someone could help me fix this as i am really interested in building bots.
I have uploaded my Bot Project on gitlab https://gitlab.com/pdmnbhrawal/myechobot01.
This is a simple typo. You've written "context-type" instead of "content-type." The YouTube tutorial you linked to tells you to write a line like this:
if "application/json" in request.headers["content-type"]:
In order to avoid this kind of typo, you can download the source code that the video links to directly instead of trying to rewrite it yourself.
You can troubleshoot this kind of error yourself by noticing in the stack trace that it tells you what line of code is throwing the error. When it says KeyError: 'HTTP_CONTEXT_TYPE' that should indicate to you that you've entered the wrong key and you should check for a typo. You can also try using a debugger and stepping through your code.
There are a few other problems with the bot that you may notice. It doesn't handle conversation update activities correctly because it doesn't account for the incoming activity having no text. It also doesn't return an HTTP response from the api/messages endpoint. You might want to fix those problems later, but your bot will run despite them.
I use telepot python library with my bot, in python 3.5. I want to read the text of a message that is already in a chat, knowing the id of the telegram chat and the id of the message. How can I do?
The telepot library is a wrapper around the Telegram Bot HTTP API and unfortunately the API doesn't have such method available at the moment. (see here for full list of all available methods). Additionally, telepot is no longer actively maintained.
Nonetheless, you can directly make requests to the telegram servers (skipping the intermediary HTTP API) by using mtproto protocol based libraries (such as Telethon, Pyrogram, MadelineProto, etc..) instead.
Here is an example using Telethon to give you an idea:
from telethon import TelegramClient
API_ID = ...
API_HASH = ' ... '
BOT_TOKEN = ' ... '
client = TelegramClient('bot_session', API_ID, API_HASH).start(bot_token = BOT_TOKEN)
async def main():
message = await client.get_messages(
-10000000000, # channel ID
ids=3 # message ID
)
print("MESSAGE:\n---\n")
print(message.text)
client.start()
client.loop.run_until_complete(main())
[user#pc ~]$ python main.py
MESSAGE:
---
test message
You can get values for API_ID and API_HASH by creating an application over my.telegram.org (see this page for more detailed instruction)
I want to develop a Telegram bot, that acts as a bookmarking system. It should process commands that reply to other messages. The instance:
I use python-telegram-bot for development and it seems that there is no way to see that message to which /important replies. I found the Update.message.reply_to_message object, which works only when a user replies to a message from the bot itself.
def important_handler(update: Update, context: CallbackContext):
reply_to_message = update.message.reply_to_message
if reply_to_message is None:
logger.error('reply_to_message is None. But it shouldn\'t.')
update.message.reply_text('There is no message attached. Try again.')
return
# ... business logic
Is there any way to get reply_to_message attribute (or an alternative) for all the replies? Thanks in advice;)
I had the same problem. It only worked when a user replied to the bot. My issue was that the bot had Privacy Mode enabled. Once I disabled it with Botfather via /setprivacy and then it worked.