telegram python - automation connect and send a message - python-3.x

trying to explore telegram python and create an automation that can send data, but for now I'am trying to connect my server with centOS to telegram during my testing I received an error when I run the python script, is there someone know what I need to check or modify to my script?
Error:
Request caused struct.error: required argument is not an integer: SendMessageRequest(peer=InputPeerUser(user_id='user_id', access_hash='user_hash'), message='Testing...', no_webpage=False, silent=None, background=None, clear_draft=False, reply_to_msg_id=None, random_id=57746331822001234, reply_markup=None, entities=[], schedule_date=None)
api_id = 'telegram app id'
api_hash = 'telegram hash'
token = 'telegram token'
message = "Testing..."
phone = '213phoneNumber'
client = TelegramClient('session', api_id, api_hash)
client.connect()
if not client.is_user_authorized():
client.send_code_request(phone)
client.sign_in(phone, input('Enter the code:'))
try:
receiver = InputPeerUser('user_id', 'user_hash')
client.send_message(receiver, message, parse_mode='html')
except Exception as e:
print(e);
client.disconnect()

Related

Twilio WhatsApp bug

I am getting this unexpected error with no explanation regarding Twilio API for WhatsApp messaging:-
print("Please enter a message.")
body_of_the_message = input()
account_sid = mysid
auth_token = myauthtoken
client = Client(account_sid, auth_token)
message = client.messages.create(from_='whatsapp:mytwilionum', body=(body_of_the_message),to='whatsapp:+myphone' )
sid = message.sid
print(f"The message SID is:- {sid}")
When I run this, I pass in “Hi there.” for the input.
This is what I get in response:-
The message SID is:- (sid)
I don’t see any notifications for the message being sent, and even when I check the chat history. Please help me with this stuff.

Python Slackbot not Showing as active and Not responding

The slackbot is not showing as active and not responding. I have used ngrok to set up tunneling from my localhost to allow for the slack bot to be verified. On slack it shows that the request URL has been verified. I have also subscribed to slack events.
I am following, https://medium.com/developer-student-clubs-tiet/how-to-build-your-first-slack-bot-in-2020-with-python-flask-using-the-slack-events-api-4b20ae7b4f86, to get this bot working. Any help would be great. Thanks.
from flask import Flask, Response
from slackeventsapi import SlackEventAdapter
import os
from threading import Thread
from slack import WebClient
# This `app` represents your existing Flask app
app = Flask(__name__)
greetings = ["hi", "hello", "hello there", "hey"]
SLACK_SIGNING_SECRET = os.environ['SLACK_SIGNING_SECRET']
slack_token = os.environ['SLACK_BOT_TOKEN']
VERIFICATION_TOKEN = os.environ['VERIFICATION_TOKEN']
#instantiating slack client
slack_client = WebClient(slack_token)
# An example of one of your Flask app's routes
#app.route("/")
def event_hook(request):
json_dict = json.loads(request.body.decode("utf-8"))
if json_dict["token"] != VERIFICATION_TOKEN:
return {"status": 403}
if "type" in json_dict:
if json_dict["type"] == "url_verification":
response_dict = {"challenge": json_dict["challenge"]}
return response_dict
return {"status": 500}
return
slack_events_adapter = SlackEventAdapter(
SLACK_SIGNING_SECRET, "/slack/events", app
)
#slack_events_adapter.on("app_mention")
def handle_message(event_data):
def send_reply(value):
event_data = value
message = event_data["event"]
if message.get("subtype") is None:
command = message.get("text")
channel_id = message["channel"]
if any(item in command.lower() for item in greetings):
message = (
"Hello <#%s>! :tada:"
% message["user"] # noqa
)
slack_client.chat_postMessage(channel=channel_id, text=message)
thread = Thread(target=send_reply, kwargs={"value": event_data})
thread.start()
return Response(status=200)
# Start the server on port 3000
if __name__ == "__main__":
app.run(port=3000)
This was the error code that I was running into:
urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1091)>.
This brought me to this StackOverflow thread:
Scraping: SSL: CERTIFICATE_VERIFY_FAILED error for http://en.wikipedia.org
Running the certification file in the python folder allowed the slack bot to interact with the channel. The bot is now working but does not show as active.

How can I send a message to #BotFather programmatically?

I know that a bot can be created in a telegram if you send the command /newbot to the bot #BotFather. But to do this, you need to take your device, open Telegram, open a chat with #BotFather and send him the command /newbot. Can all of the above be done programmatically?
P.S.: this is not laziness, but an attempt to optimize the solution.
Yes, it's possible to create such interaction with mtproto libraries (pyrogram, telethon, madelineproto, etc...)
Here is a PoC script using telethon (python3 -m pip install -U telethon first to install the dependency):
from telethon import TelegramClient, events
api_id = ...
api_hash = "..."
client = TelegramClient('session', api_id, api_hash)
BOT_NAME="..."
BOT_USER_NAME="..." # must end with -bot
#client.on(events.NewMessage)
async def message_handler(event):
if 'Please choose a name for your bot' in event.raw_text:
await event.reply(BOT_NAME)
elif 'choose a username for your bot' in event.raw_text:
await event.reply(BOT_USER_NAME)
elif 'Done! Congratulations on your new bot' in event.raw_text:
print("Bot created!")
await client.disconnect()
async def main():
await client.send_message('botfather', '/newbot')
with client:
client.loop.run_until_complete(main())
client.run_until_disconnected()
You acquire the app_id and app_hash values from https://my.telegram.org/
and here is telethon's doc.

Getting timedout during smtplib.SMTP(“smtp.gmail.com”, 587) in Python

The following code is working perfectly in another computer:
def send_email(user, pwd, recipient, subject, body):
#lb.send_email('AlirezaFedEx#gmail.com','P&ENLAMS','info#nka-it.com','Test','This is a test')
import smtplib
FROM = 'AlXXX#gmail.com'
TO = ['info#XXX.com'] # recipient if isinstance(recipient, list) else [recipient]
SUBJECT = 'Test'#subject
TEXT = 'This is a test' #body
# Prepare actual message
message = """From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
try:
server = smtplib.SMTP('smtp.gmail.com',587)
server.ehlo()
server.starttls()
server.login(user, pwd)
server.sendmail(FROM, TO, message)
server.close()
print('successfully sent the mail')
except Exception as err:
print("failed to send mail:" + str(err))
When running the following part:
server = smtplib.SMTP('smtp.gmail.com',587)
it starts to freeze and eventually gives the following error:
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
I checked proxy of my browser and disabled proxy but still getting the error. Any advice please?
are you using proxy? If so, please disable the proxy and try again. This should work properly if you have an active internet connection.

Python how to forward messages from server

Hello i have a old discord server which we don't using now. and we created a new server and moved all members there but still some members r there in old server. So is there a option to forward all messages from server A to server B to specific channel.
Update:
I mean like when ever server A gets a message it should be sended to server B to a specific channel. bot is in both server so with that i can forward all incoming message exactly.
Bot Code
token = "xxxxxxxxxxxxx"
prefix = "!"
import discord
from discord.ext import commands
from discord.ext.commands import Bot
bot = commands.Bot(command_prefix=prefix)
bot.remove_command("help")
#bot.event
async def on_ready():
print('\nLogged in as')
print("Bot Name: " + bot.user.name)
print("Bot User ID: " + bot.user.id)
old_server = bot.get_server('xxxxxxxxxxxxx')
new_channel = bot.get_channel('xxxxxxxxxxxxx')
#bot.event
async def on_message(message):
message.content = message.content.lower()
if message.server == old_server:
await bot.send_message(new_channel, message.content)
await bot.process_commands(message)
bot.run(token)
You can use the on_message event to check when messages are sent to the old server and have the bot post the message to the new server.
Below is example code where the bot will check when the old server gets a message, then posts the same message to a specified channel on the new server.
from discord.ext import commands
client = commands.Bot(command_prefix='!')
#client.event
async def on_message(message):
old_server = client.get_server('old_server_id')
new_channel = client.get_channel('new_channel_id')
if message.server == old_server:
await client.send_message(new_channel, message.content + ' - ' + message.author.nick)
client.run('token')

Resources