How to get a message from a Chat, after using a command and storing that message as a variable (Pyrogram)? - telegram

So I am kinda new with Pyrogram and I want to create my own Genshin Bot. After using the command redeem code, I want the message to be taken and stored as variable. so can anyone help me with that
after taking the code as input from user I would be able to use genshin.py api wrapper to redeem code. Just need help with getting message and storing it as variable.
import genshin
import os
from dotenv import load_dotenv
from pyrogram import Client, filters
load_dotenv()
global chatid
chatid = 842544591
global uid
uid = os.getenv("uid")
ltuid = os.getenv("ltuid")
ltoken = os.getenv("ltoken")
cookie_token = os.getenv("cookie_token")
api_id = os.getenv("api_id")
api_hash = os.getenv("api_hash")
bot_token = os.getenv("bot_token")
cookies = {"ltuid": ltuid,
"ltoken": ltoken,
"cookie_token": cookie_token,
"uid": uid}
client = genshin.Client(cookies)
bot = Client(
"Genshin Bot",
api_id=api_id,
api_hash=api_hash,
bot_token=bot_token
)
#bot.on_message(filters.command('start'))
def start_command(bot, message):
message.reply_text(
"Welcome to Genshin Auto Tasks Bot.\nFor Getting Started Use /help command.")
#bot.on_message(filters.command('help'))
def help_command(bot, message):
message.reply_text("This is Bot's Help Section")
#bot.on_message(filters.command('notes'))
async def get_notes(bot, message):
data = await client.get_full_genshin_user(uid)
notes = await client.get_notes(uid)
active_days = (data.stats.days_active)
total_characters = (data.stats.characters)
abyss_total_stars = (data.abyss.previous.total_stars)
resin_count = notes.current_resin
resin_recovery_time = notes.remaining_resin_recovery_time
await message.reply_text("Pranay Asia" + "\n" +
"uid : " + str(uid) + "\n" +
"-----------------------------------------------------------------" + "\n" +
"Resin Count: " + str(resin_count) + "/" + str(notes.max_resin) + "\n" +
"Countdown to next resin recovery: " + str(resin_recovery_time) + "\n" +
"Total No. of Active Days: " + str(active_days) + "\n" +
"Total No. of Characters: " + str(total_characters) + "\n" +
"Total Stars in Abyss: " + str(abyss_total_stars)
)
#bot.on_message(filters.command('redeemcode'))
def redeem_code(bot, message):
message.reply_text("Send the Code to Redeem")
bot.run()

try message.text
I use it as a userbot but nothing changes so much. This piece of code saves the sent message to a variable and filters out the command itself. For a bot it will be easier: answer = message.text
#app.on_message(filters.command("ns", prefixes=".") & filters.text)
async def EXAMPLE(_,msg):
orig_text = msg.text.split(".ns ", maxsplit=1)[1]
text = orig_text

Related

Obspy Issue: Acceleration Data from GeoNet

I am trying to create ASCII files of acceleration data from various New Zealand earthquakes, code attached below. I was previously able to generate ASCII files of the acceleration data, however, now running the same code I get the message:
UserWarning: The StationXML file has version 1, ObsPy can read versions (1.0, 1.1). Proceed with caution.
And the acceleration files are no longer being written. Please let me know if there is a way to fix this issue.
import os
from obspy import UTCDateTime
from obspy.clients.fdsn import Client as FDSN_Client
from obspy import read_inventory
from obspy.geodetics import kilometers2degrees
client = FDSN_Client("GEONET")
evid="2016p858000"
minrad=kilometers2degrees(0)
maxrad=kilometers2degrees(30)
cat = client.get_events(eventid=evid)
print(cat)
event = cat[0]
origin = event.origins[0]
otime = origin.time
print(otime)
otime = cat[0].origins[0].time
print(otime)
inventory = client.get_stations(latitude=cat[0].origins[0].latitude,
longitude=cat[0].origins[0].longitude,
minradius=minrad,
maxradius=maxrad,
channel="H??",
level="channel",
starttime = otime-60,
endtime = otime+4*60).remove(channel='HNZ')
print(inventory)
from obspy import Stream
st = Stream()
for network in inventory:
for station in network:
try:
st += client.get_waveforms(network.code, station.code, "*", "H??",
otime-60, otime + 4*60, attach_response=True).remove(channel='HNZ')
st_rem1=st.copy()
pre_filt = (0.025, 0.03, 70.0, 80.0)
acc = st_rem1.copy()
acc.remove_response(output='ACC', pre_filt=pre_filt)
print(acc[0])
acc.plot()
acc[0].write('MS_' + evid + '_' + network.code + '_' + station.code + '_' + station[0].code + '.ascii', format='SLIST')
acc[1].write('MS_' + evid + '_' + network.code + '_' + station.code + '_' + station[1].code + '.ascii', format='SLIST')
except:
pass

Accessing config variables in steps file

Containername argument is the one which I am not understanding how to be accessed from configuration file
Test_steps.file
import datetime
from behave import *
import os, json, random, datetime
from Utilities.KafkaConsumer.SupplyChain import Consumer_TransactionReceipts as CTR
from Utilities.KafkaConsumer.SupplyChain import Consumer_EODSnapshot as CES
from Utilities import CosmosDB as Cdb
#given('Delivery receipts are consumed from Kafka topic')
def delivery_receipts_consumption(context):
obj = CTR.TransactionReceipt()
context.message = obj.consume_kafka()
print(context.message)
#then('Calculate the Cost of goods receipted for a SKU and store')
def purchase_volume_validation(context):
location = '6228'
skunumber = '8091776'
today = datetime.date.today()
yesterday = str(today - datetime.timedelta(days=1))
print("Yesterday's date:", yesterday)
cosmosquerydr = "select dr.quantityOfUnits,dr.ownerOnDespatch,dr.packSize from dr where dr.SKUNumber = " + skunumber + " and dr.globalLocationNumber = " + location + " and dr.createdDate like '" + yesterday + "%' "
directreceipts = Cdb.CosmosDB.query_cosmos_db(cosmosquerydr, containername)
directreceipt = [json.loads(d) for d in directreceipts]

Why python asyncio coroutine is pausing at the line socket.recv(1024) ? why the while loops are failed to cross yeild statements?

I have a small application where, one coroutine will send data and the other coroutine will receive data and logs whether it received the exact transmitted data or not.
Both coroutines are in while loops. Some how, the trans() coroutine and recv() coroutine are not proceeding ahead when they hit the line yield from XXXXXXX
data, server = yield from recv_sock.recvfrom(1024)
Here is the code
import asyncio
import socket
import time
import datetime
import logging
trans_addr = ('localhost', 5555)
recv_addr = ('localhost',6666)
#asyncio.coroutine
def trans():
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(trans_addr)
i = 0
global sen_data
while True:
print("hi")
sen_data = "HELLO " + str(i)
sent = yield from sock.sendto(sen_data.encode(), recv_addr)
print(sent)
print("hi1")
yield from time.sleep(2)
i += 1
print("hi1")
#asyncio.coroutine
def recv():
recv_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
recv_sock.bind(recv_addr) # binding the receiving end to 1.241 and port 6666
#recv_sock.setblocking(0)
while True:
try:
print("hello")
data, server = yield from recv_sock.recvfrom(1024)
print("hello2")
if (data):
recv_data = data.decode()
if (sen_data == recv_data):
logging.info("transmitted data :" + sen_data + " is Received as :" + recv_data + " at :" + str(
datetime.datetime.now()) + '\n')
print("transmitted data :" + sen_data + " is Received as :" + recv_data + " at :" + str(
datetime.datetime.now()) + " from :" + str(server) + '\n')
else:
logging.critical("Data missed : ")
logging.critical("Transmitted data " + sen_data + " is != " + "received data : " + recv_data + '\n')
print("data is missing--->")
print("Transmitted data " + sen_data + " is != " + "received data : " + recv_data + '\n')
except:
pass
# print("not receiving data due to some fault in the receiving socket")
# time.sleep(1)
loop=asyncio.get_event_loop()
tasks = [loop.create_task(trans()), loop.create_task(recv())]
wait_tasks = asyncio.wait(tasks)
loop.run_forever()
loop.run_until_complete(wait_tasks)
Output is:
hello
hi
Can anyone let me know,why the coroutines are failed to cross the yield from commands? i am using python 3.3.2
yield from or await should be used with coroutines. recvfrom is not a coroutine. For example, you can use loop.sock_recv() instead:
reader, writer = socket.socketpair()
writer.setblocking(False)
reader.setblocking(False)
await loop.sock_recv(...)
await loop.sock_sendall(...)

Searching throughout telnet output result while doing parallel telnet to multiple network devices

I am trying to find a string (e.g.: ZNTS) from telnet output to a host.
I want to telnet to multiple hosts at the same time because waiting to finish from host to host takes a long time. The host can not response fast enough, so I need to sleep after every command line.
Below is my code:
import sys
import telnetlib
import time
MXK_LIST = ['172.16.32.15',
'172.16.33.30',
'192.168.55.3',
'192.168.52.3',
'192.168.54.3',
'192.168.42.25',
'192.168.43.3',
'192.168.44.3',
'192.168.45.3',
'192.168.46.3',
'192.168.47.3',
'192.168.48.3',
'192.168.49.9']
TOTAL_MXK = len(MXK_LIST)
ZNTS = str(sys.argv[1])
DEBUG = str(sys.argv[2])
username = "admin"
password = "4n0cmek0n9net"
I = 0
C = 0
print "\n Finding ZNTS = " + ZNTS
print "\n It will take around 5 minutes to complete the searching !!\n"
for MXK in MXK_LIST:
I = I + 1
OUTPUT = ""
try:
tn = telnetlib.Telnet(MXK)
except:
print "Bad Connection. Please verify IP again."
sys.exit(0)
tn.read_until(b"login: ",1)
tn.write(username + "\n")
time.sleep(5)
tn.read_until(b"password: ",1)
tn.write(password + "\n")
time.sleep(5)
OUTPUT = tn.read_until(b">",1)
if DEBUG == 1: print OUTPUT
time.sleep(5)
tn.write("onu showall 1" + "\n")
time.sleep(5)
tn.read_until(b"[no] ",1)
tn.write(b"yes" + "\n")
time.sleep(15)
OUTPUT = tn.read_until(b"quit",1)
time.sleep(5)
if DEBUG == 1: print OUTPUT
tn.write("A" + "\n")
time.sleep(5)
OUTPUT = tn.read_until(b">",1)
if DEBUG == 1: print OUTPUT
tn.write("exit\n")
if ZNTS in OUTPUT:
print str(I) + "/" + str(TOTAL_MXK) + " : FOUND " + ZNTS + " IN " + MXK
C = C + 1
else:
print str(I) + "/" + str(TOTAL_MXK) + " : NOT FOUND " + ZNTS + " IN " + MXK
print "\n"+ZNTS + " is found in " + str(C) + " MXK"
You can try to spawn a thread for each telnet session and parallelize the search that way.
Check out the multi-thread sample code here:
http://stackoverflow.com/questions/6286235/multiple-threads-in-python

Python: infinite loop while executing SQLite statement

I have this 2 SQLite scripts:
both tested by direct input into SQLite.
def getOutgoingLinks(self, hostname):
t = (hostname,)
result = self.__cursor.execute("SELECT url.id, hostname.name, url.path, linking_to.keyword, siteId.id " +
"FROM url, hostname, linking_to, " +
"(SELECT url.id FROM url, hostname " +
"WHERE hostname.name = (?) " +
"AND hostname.id = url.hostname_id " +
") AS siteId " +
"WHERE linking_to.from_id = siteId.id " +
"AND linking_to.to_id = url.id " +
"AND url.hostname_id = hostname.id", t)
result = result.fetchall()
return result
def getIncommingLinks(self, hostname):
t = (hostname,)
result = self.__cursor.execute("SELECT url.id, hostname.name, url.path, linking_to.keyword, siteId.id " +
"FROM url, hostname, linking_to, " +
"(SELECT url.id FROM url, hostname " +
"WHERE hostname.name = (?) " +
"AND hostname.id = url.hostname_id " +
") AS siteId " +
"WHERE linking_to.to_id = siteId.id " +
"AND linking_to.from_id = url.id " +
"AND url.hostname_id = hostname.id", t)
result = result.fetchall()
return result
The getIncommingLinks() methond works very well, but getOutgoingLinks() causes an infinite Loop when python trys to execute the SQL statement. Any ideas what went wrong?
Rewrite your Select statements without select ...( Select ...) - thats very bad style. The result may solve your problem.
If by infinite loop you mean that the function doesnt ever get to return a value, I had the same problem.
Found the solution in Why python+sqlite3 is extremely slow?. With large tables it becomes a performance issue with the version shipped with python 2.7. I solved it by upgrading sqlite3 as specified here: https://stackoverflow.com/a/3341117/3894804

Resources