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
Related
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
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?
Some time ago I was working to rotate the password of the administrator#vsphere.local user in the Vcenter, but there isn't a lot of information about how to do that with Python. I did with LDAP protocol, I just want to create this to future references if someone need it.
import ldap
import os
import sys
vcenter = "the_IP_OR_Host_Name_of_the_VC"
ad_server = "ldap://"+vcenter
userAccount = 'Administrator'
ad_dn = "cn="+userAccount+",cn=users,dc=vsphere,dc=local"
username = 'CPMS_Test#vsphere.local'
old_pwd = 'The_Actual_PAss_of_Administrator'
new_pwd = 'New_Pass_of_the_Account'
# Lets initialize the LDAP, in our case is the same VC
l = ldap.initialize(ad_server)
#LDAP settings, Im not using SSL, but you can use it
l.protocol_version = ldap.VERSION3
l.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_DEMAND)
l.set_option(ldap.OPT_X_TLS_NEWCTX, 0)
l.simple_bind_s(ad_dn.format(username), old_pwd)
#lets run the update of the pass
password_value_old = old_pwd.encode("utf-8")
password_value = new_pwd.encode("utf-8")
mod_list = [
(ldap.MOD_DELETE, 'userpassword', [password_value_old]),
(ldap.MOD_ADD, 'userpassword', [password_value]),
]
result = l.modify_s(ad_dn.format(username), mod_list)
print(result.info)
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
I want to authenticate an user in Python(2.6 or 2.7) / C code .
I have to create a simple authentication module which will take username and password as input and will validate user (like PAM module for UNIX).
Any way to do it ?
Are you looking for something like LogonUser?, to authenticates local user, for example:
#!python
# -*- coding: utf-8 -*-
from os import environ
from ctypes import windll, byref, POINTER, FormatError, GetLastError
from ctypes.wintypes import (
LPCWSTR, WCHAR, DWORD, HANDLE, BOOL
)
MAX_COMPUTERNAME_LENGTH = 15
LOGON32_LOGON_NETWORK_CLEARTEXT = 8
LOGON32_PROVIDER_DEFAULT = 0
CloseHandle = windll.Kernel32.CloseHandle
CloseHandle.argtypes = [HANDLE]
CloseHandle.restype = BOOL
LogonUser = windll.Advapi32.LogonUserW
LogonUser.argtypes = [LPCWSTR, LPCWSTR, LPCWSTR, DWORD, DWORD, POINTER(HANDLE)]
LogonUser.restype = BOOL
if __name__ == '__main__':
username = 'MyUsername'
password = 'MyPassword'
token = HANDLE()
status = LogonUser(username,
environ['COMPUTERNAME'],
password,
LOGON32_LOGON_NETWORK_CLEARTEXT,
LOGON32_PROVIDER_DEFAULT,
byref(token))
error = GetLastError()
if status:
print('OK, successes')
CloseHandle(token)
else:
print(FormatError(error))