Python | use a printed value before - python

i'm actually trying to dev a slack bot with python. I'm learning python and slack api at the same time and i want to know how can i use a value printed before ?
import os
from slackeventsapi import SlackEventAdapter
from slack import WebClient
from slack.errors import SlackApiError
import time
client = WebClient(token=os.environ['SLACK_KEY'])
response = client.chat_postMessage(
channel='starterbot',
text="Hello, are you there ?")
assert response["message"]["text"] == "Hello, are you there ?"
RTM_READ_DELAY = 2
time.sleep(RTM_READ_DELAY)
print(response['ts'])
# if response == "Yes":
# elif response != "Yes":
# client.chat_postMessage(
# channel='starterbot',
# text="Bye!")
if client.conversations_replies(channel='C01665VJ2JH', ts='1593523175.013300') == "Yes":
client.chat_postMessage(channel='starterbot', text="u sure ?")
i want to create a variable to save the ts value that i print, and then use it in the client.conversations_replies.
Ty for your help

Related

I am creating a reddit video maker bot and I am getting this error no moduled name

I am also using flask and I am trying to run the code from github.
Error :
(env) PS E:\VIDEOBOT> & e:/VIDEOBOT/env/Scripts/python.exe e:/VIDEOBOT/reddit/subreddit.py
Traceback (most recent call last):
File "e:\VIDEOBOT\reddit\subreddit.py", line 1, in
from utils.console import print_markdown, print_step, print_substep
ModuleNotFoundError: No module named 'utils'
Below is the code.
subreddit.py
from utils.console import print_markdown, print_step, print_substep
import praw
import random
from dotenv import load_dotenv
import os
def get_subreddit_threads():
"""
Returns a list of threads from the AskReddit subreddit.
"""
load_dotenv()
print_step("Getting AskReddit threads...")
if os.getenv("REDDIT_2FA").lower() == "yes":
print("\nEnter your two-factor authentication code from your authenticator app.\n")
code = input("> ")
print()
pw = os.getenv("REDDIT_PASSWORD")
passkey = f"{pw}:{code}"
else:
passkey = os.getenv("REDDIT_PASSWORD")
content = {}
reddit = praw.Reddit(
client_id=os.getenv("REDDIT_CLIENT_ID"),
client_secret=os.getenv("REDDIT_CLIENT_SECRET"),
user_agent="Accessing AskReddit threads",
username=os.getenv("REDDIT_USERNAME"),
password=passkey,
)
if os.getenv("SUBREDDIT"):
subreddit = reddit.subreddit(os.getenv("SUBREDDIT"))
else:
# ! Prompt the user to enter a subreddit
try:
subreddit = reddit.subreddit(
input("What subreddit would you like to pull from? ")
)
except ValueError:
subreddit = reddit.subreddit("askreddit")
print_substep("Subreddit not defined. Using AskReddit.")
threads = subreddit.hot(limit=25)
submission = list(threads)[random.randrange(0, 25)]
print_substep(f"Video will be: {submission.title} :thumbsup:")
try:
content["thread_url"] = submission.url
content["thread_title"] = submission.title
content["comments"] = []
for top_level_comment in submission.comments:
content["comments"].append(
{
"comment_body": top_level_comment.body,
"comment_url": top_level_comment.permalink,
"comment_id": top_level_comment.id,
}
)
except AttributeError as e:
pass
print_substep("Received AskReddit threads successfully.", style="bold green")
return content
console.util.py
from rich.console import Console
from rich.markdown import Markdown
from rich.padding import Padding
from rich.panel import Panel
from rich.text import Text
console = Console()
def print_markdown(text):
"""Prints a rich info message. Support Markdown syntax."""
md = Padding(Markdown(text), 2)
console.print(md)
def print_step(text):
"""Prints a rich info message."""
panel = Panel(Text(text, justify="left"))
console.print(panel)
def print_substep(text, style=""):
"""Prints a rich info message without the panelling."""
console.print(text, style=style)
I have got this code from redditbot version--1.0.0

Linux NoHup fails for Streaming API IG Markets where file is python

This is quite a specific question regarding nohup in linux, which runs a python file.
Back-story, I am trying to save down streaming data (from IG markets broadcast signal). And, as I am trying to run it via a remote-server (so I don't have to keep my own local desktop up 24/7),
somehow, the nohup will not engage when it 'listen's to a broadcast signal.
Below, is the example python code
#!/usr/bin/env python
#-*- coding:utf-8 -*-
"""
IG Markets Stream API sample with Python
"""
user_ = 'xxx'
password_ = 'xxx'
api_key_ = 'xxx' # this is the 1st api key
account_ = 'xxx'
acc_type_ = 'xxx'
fileLoc = 'marketdata_IG_spx_5min.csv'
list_ = ["CHART:IX.D.SPTRD.DAILY.IP:5MINUTE"]
fields_ = ["UTM", "LTV", "TTV", "BID_OPEN", "BID_HIGH", \
"BID_LOW", "BID_CLOSE",]
import time
import sys
import traceback
import logging
import warnings
warnings.filterwarnings('ignore')
from trading_ig import (IGService, IGStreamService)
from trading_ig.lightstreamer import Subscription
cols_ = ['timestamp', 'data']
# A simple function acting as a Subscription listener
def on_prices_update(item_update):
# print("price: %s " % item_update)
print("xxxxxxxx
))
# A simple function acting as a Subscription listener
def on_charts_update(item_update):
# print("price: %s " % item_update)
print(xxxxxx"\
.format(
stock_name=item_update["name"], **item_update["values"]
))
res_ = [xxxxx"\
.format(
stock_name=item_update["name"], **item_update["values"]
).split(' '))]
# display(pd.DataFrame(res_))
try:
data_ = pd.read_csv(fileLoc)[cols_]
data_ = data_.append(pd.DataFrame(res_, columns = cols_))
data_.to_csv(fileLoc)
print('there is data and we are reading it')
# display(data_)
except:
pd.DataFrame(res_, columns = cols_).to_csv(fileLoc)
print('there is no data and we are saving first time')
time.sleep(60) # sleep for 1 min
def main():
logging.basicConfig(level=logging.INFO)
# logging.basicConfig(level=logging.DEBUG)
ig_service = IGService(
user_, password_, api_key_, acc_type_
)
ig_stream_service = IGStreamService(ig_service)
ig_session = ig_stream_service.create_session()
accountId = account_
################ my code to set sleep function to sleep/read at only certain time intervals
s_time = time.time()
############################
# Making a new Subscription in MERGE mode
subscription_prices = Subscription(
mode="MERGE",
# make sure to put L1 in front of the instrument name
items= list_,
fields= fields_
)
# adapter="QUOTE_ADAPTER")
# Adding the "on_price_update" function to Subscription
subscription_prices.addlistener(on_charts_update)
# Registering the Subscription
sub_key_prices = ig_stream_service.ls_client.subscribe(subscription_prices)
print('this is the line here')
input("{0:-^80}\n".format("HIT CR TO UNSUBSCRIBE AND DISCONNECT FROM \
LIGHTSTREAMER"))
# Disconnecting
ig_stream_service.disconnect()
if __name__ == '__main__':
main()
#######
Then, I try to run it on linux using this command : nohup python marketdata.py
where marketdata.py is basically the python code above.
Somehow, the nohup will not engage....... Any experts/guru who might see what I am missing in my code?

How to see the error frames of a CAN network with Python-CAN

I wrote the program below,
can = CAN("can0", bitrate=50000, listen_only=True, error_reporting=True)
while True:
msg = can.recv()
print "Msg: ", msg
But it only displays the standard S or Extended X flags even though when I run the command in Terminal to check the network activity, I can see that the error counter is increasing.
import can
import CAN
import time
import logging
#logging.basicConfig(level=logging.DEBUG)
print("Initializing Listener")
can1 = CAN('can0', bitrate=500000, listen_only=True, err_reporting=True)
#print "Bus is : ", can1.bus.get_can_bus()
can1.bus.set_filters(can_filters=[{"can_mask":0x7FF, "can_id":0x00000000, "extended":False}])
CAN_ERR_FLAG = 0x20000000
while 1:
msg = can1.recv()
if (msg.arbitration_id & CAN_ERR_FLAG) == CAN_ERR_FLAG:
print "Can Error Caught"
elif msg.is_error_frame:
print "Finally Error Frame"
How can I read the error-frames of the CAN-bus ?
Things work fine when I use commnad candump -e any,0:0,#FFFFFFFF
Use Python - 3
import binascii
channel_name = "vcan0"
socketID = socket.socket(socket.AF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
# socketID.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_ERR_FILTER, 0x1FFFFFFF)
error = socketID.bind((channel_name,))
print(binascii.hexlify(socketID.recv(32)))

Change custom keyboard by sending commands on telepot Telegram Bot

I'm using this line for a custom keyboard on my Telegram bot:
markup = ReplyKeyboardMarkup(keyboard=[['Time', KeyboardButton(text='NewKey')],["File", "Audio"]])
I want my bot to change custom keyboard to another when user sends NewKey. And it will send show up a new custom keyboard but it's layout will be same as the default keyboard.
I have tried this but it is not working:
elif command == 'NewKey':
markup = ReplyKeyboardMarkup(keyboard=[['More', KeyboardButton(text='More2')],["More3", "More5"]])
Here is my full code of my bot:
import time, datetime
import telepot
from telepot.loop import MessageLoop
from telepot.namedtuple import ReplyKeyboardMarkup, KeyboardButton
now = datetime.datetime.now()
def action(msg):
chat_id = msg['`chat']['id']
command = msg['text']
print('Received: %s' % command)
markup = ReplyKeyboardMarkup(keyboard=[['Time', KeyboardButton(text='NewKey')],["File", "Audio"]])
if command == '/start':
telegram_bot.sendMessage (chat_id, str("Hi! Which one do you want? choose from the below keyboard buttons."), reply_markup=markup)
telegram_bot.sendMessage(chat_id, str(now.hour)+str(":")+str(now.minute))
elif command == 'NewKey':
markup = ReplyKeyboardMarkup(keyboard=[['More', KeyboardButton(text='More2')],["More3", "More5"]]))
elif command == 'Time':
telegram_bot.sendMessage(chat_id, str(now.hour)+str(":")+str(now.minute))
elif command == '/file':
telegram_bot.sendDocument(chat_id, document=open('/home/pi/Aisha.py'))
elif command == '/audio':
telegram_bot.sendAudio(chat_id, audio=open('/home/pi/test.mp3'))
telegram_bot = telepot.Bot('MY-BOT-TOKEN')
print((telegram_bot.getMe()))
MessageLoop(telegram_bot, action).run_as_thread()
print('Up and Running....')
while 1:
time.sleep(10)
`

Yowsup auth fail whatsapp

i am working on an api for whatsapp, i am using Yowsup.
when i use Yowsup Cli client i manage to login to the whatsapp account and send and receive messages from it.
when i try to use the following script, it return "Auth Failed!".
import sys
import os
import logging
import time
import shutil
import Queue
from collections import defaultdict
from Yowsup.Common.debugger import Debugger
from Yowsup.connectionmanager import YowsupConnectionManager
from py_utils import logutils
from py_utils import executable_utils
from py_utils import exception_utils
from py_utils.cli_utils import actions_handler
COUNTRY_CODE = "COUNTRY_NUM"
PHONE_NUMBER = "MYNUMBER"
# IDENTITY = ""
PASSWORD = 'MY_PASS_WORD'
LOGIN = COUNTRY_CODE + PHONE_NUMBER
import argparse, sys, os, csv
from Yowsup.Common.utilities import Utilities
from Yowsup.Common.debugger import Debugger
from Yowsup.Common.constants import Constants
from Yowsup.Contacts.contacts import WAContactsSyncRequest
from Yowsup.connectionmanager import YowsupConnectionManager
import threading,time, base64
########## DO NOT COMMIT THIS FILE WITH YOUR CREDENTIALS ###########
#.....................WhatsApp Account Config.......................
nickname = "lamaaaaaaa"
username = LOGIN
password = PASSWORD
id = "" # Not required
#....................................................................
# Degug is False by default if you add -d you will set it to True
Debugger.enabled = True if '-d' in sys.argv else False
password = base64.b64decode(bytes(password.encode('utf-8')))
def login(username, password):
print "[] Logging in as %s (%s)\n" % (nickname, username)
methodsInterface.call("auth_login", (username, password))
def onAuthSuccess(username):
print("Authed!!\n\n")
methodsInterface.call("ready")
methodsInterface.call("presence_sendAvailableForChat", (nickname,))
def onAuthFailed(username, err):
print("Auth Failed!")
########################### BIND EVENTS #############################
connectionManager = YowsupConnectionManager()
signalsInterface = connectionManager.getSignalsInterface()
methodsInterface = connectionManager.getMethodsInterface()
connectionManager.setAutoPong(True)
signalsInterface.registerListener("auth_success", onAuthSuccess)
signalsInterface.registerListener("auth_fail", onAuthFailed)
#####################################################################
login(username, password)
The problem is the the access token need to be update.
in the Yowsup package there under comon \ constans.py
there a need to update the tokanData to :
tokenData = {
"v": "2.12.53",
"r": "S40-2.12.53",
"u": "WhatsApp/2.12.53 S40Version/14.26 Device/Nokia302",
"t": "PdA2DJyKoUrwLw1Bg6EIhzh502dF9noR9uFCllGk1416435341393{phone}",
"d": "Nokia302"
# "v": "2.12.15",
# "r": "S40-2.12.15",
# "u": "WhatsApp/2.12.15 S40Version/14.26 Device/Nokia302",
# "t": "PdA2DJyKoUrwLw1Bg6EIhzh502dF9noR9uFCllGk1391039105258{phone}",
# "d": "Nokia302"
}
you can see the difference between what i had and what i need to use

Categories