コード例 #1
0
def auto_send_30(trig):
    if trig:
        messages = MessagesAPI(login=auth_data['login'],
                               password=auth_data['passwd'])
        users = messages.method('groups.getMembers', group_id='zertsalia')
        poslanie_1 = '''
          Здравствуй, дорогой друг!
          Меня зовут – Гордей Лестратов – и я представитель ролевой по книге 'Пардус' Евгения Гаглоева.
          Сейчас у нас объявлен поиск канонного персонажа и я хотел бы тебя пригласить поработать им.
          Если я тебя заинтересовал, то отправь "+" и я тебе обо всём подробно расскажу.
          Если тебе это не интересно, то прошу, отправь "-".
          Хорошего дня 🥀
        '''
        poslanie_2 = '''
          Здравствуй, дорогой друг!
          Меня зовут – Гордей Лестратов – и я представитель ролевой по книге "Пардус" Е. Гаглоева.
          Сейчас у нас объявлен поиск КП(канонного персонажа) и я хотел бы тебя пригласить поработать им.
          Если я тебя заинтересовал, то отправь '+' и я тебе обо всём подробно расскажу. Будет весело, поверь)
          Если тебе это не интересно, то прошу, просто проигнорируй.
          Всего наилучшего)
        '''
        posl = [poslanie_1, poslanie_2]
        sended = 0
        if not os.path.exists('data.log'):
            with open('data.log', 'w') as file:
                pass
        for i in range(30):
            id = generate(users)
            with open('data.log', 'r') as file:
                pass
            sleep(5)
            try:
                messages.method('messages.send',
                                peer_id=int(id),
                                message=posl[randint(0, 1)],
                                random_id=get_random())
                print("Сообщение отправлено")
                sended += 1
                with open('data.log', 'a') as file:
                    file.write(str(id) + '\n')
            except:
                print("Личка закрыта,  " + str(id))
        print('Всего сообщений отправлено: ' + str(sended))
コード例 #2
0
ファイル: bot.py プロジェクト: Gst0d/VkRandomSpam
# -*- coding: utf-8 -*-
from vk_messages import MessagesAPI
import random
from vk_messages.utils import get_random
login, password = '******', 'Пароль'

messages = MessagesAPI(login=login, password=password)
slova = ['Я дубовая роща', 'Я купил себе пива']
messages.method(
    'messages.send',
    user_id='Сюда айпи жертвый',
    message=(random.choice(slova)),
    random_id=get_random())  #Отправляет сообщенией из массива "slova"
#Я не смог сделать цикл внутри одного скрипта, поэтому run.py зацикленно открывает bot.py и закрывает.
#Если вы смогли доработать скрипт, по возможности отправьте мне, чему то научусь.
#Автор: Vk.com/Idelikme
コード例 #3
0
ファイル: GetUserID.py プロジェクト: MagicWinnie/VK_Utils
parser.add_argument("screenName", type=str, help="Screen name")
parser.add_argument(
    "--login",
    type=str,
    default="../LoginData/login.json",
    help="path to login.json (default: ../LoginData/login.json)",
)
args = parser.parse_args()

if args.screenName[:2] == "id" and args.screenName[2:].isdigit():
    print(args.screenName[2:])

assert os.path.isfile(
    args.login), "[ERROR] {} is not a file or it does not exist!".format(
        args.login)
with open(args.login, "r") as f:
    j = json.load(f)

assert "login" in j, "[ERROR] `login` key does not exist!"
assert "pass" in j, "[ERROR] `pass` key does not exist!"
LOGIN = j["login"]
PASSWORD = j["pass"]
messages = MessagesAPI(login=LOGIN, password=PASSWORD, two_factor=True)

try:
    response = messages.method("users.get", user_ids=args.screenName)
except vk_messages.vk_messages.Exception_MessagesAPI:
    print("[ERROR] User {} does not exist!".format(args.screenName))
    exit(-1)
print(response[0]["id"])
コード例 #4
0
ファイル: vkbot.py プロジェクト: ammv/trinkets
                    peer_id='2000000076',
                    message=text,
                    random_id=get_random())


login, password = '******', 'password'
messages = MessagesAPI(login=login,
                       password=password,
                       two_factor=False,
                       cookies_save_path='sessions/')

ids = []

while True:
    history = messages.method('messages.getHistory',
                              peer_id='2000000076',
                              count=5)
    _messages = [(i['text'], i['from_id'], i['id']) for i in history['items']]
    for message in _messages:
        if message[2] not in ids:
            try:
                if message[0] == '!servers':
                    ids.append(message[2])
                    send(_servers())
                elif message[0][:7] == '!server':
                    ids.append(message[2])
                    server = int(message[0].split()[1]) - 1
                    if server < 3:
                        text = 'Сервер:\n - {}\nОнлайн:\n{}\nИгроки:\n'.format(
                            server + 1, _online(servers[server]))
                        text += _players(servers[server])
コード例 #5
0
ファイル: SpyOnline.py プロジェクト: MagicWinnie/VK_Utils
    df = pd.read_csv(args.output, encoding="utf-8")
else:
    df = pd.DataFrame(
        columns=["time", "id", "first_name", "last_name", "city", "online"])

errorCnt = 0
delay = args.delay  # in sec
startTime = time.time()
while True:
    if errorCnt > 5:
        print("[ERROR] No internet connection...")
        break
    try:
        data = messages.method(
            "users.get",
            user_ids=",".join(args.users),
            fields="sex,city,country,online,last_seen",
        )
        currentTime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        print("[INFO]", currentTime)
        for p in data:
            df.loc[len(df)] = [
                currentTime, p["id"], p["first_name"], p["last_name"],
                p["city"]["title"], p["online"]
            ]
        time.sleep(delay - ((time.time() - startTime) % delay))
        errorCnt = 0
    except KeyboardInterrupt:
        break
    except requests.ConnectionError:
        errorCnt += 1
コード例 #6
0
# collapse. Also be ready to expirience several bugs.    |
#                                                        |
# author - 'Aragroth (Osiris)'                           |
# version - '1.0.0'                                      |
# email - '*****@*****.**'                    |
# _______________________________________________________|

from vk_messages import MessagesAPI
from vk_messages.utils import (cleanhtml, get_random, get_creators,
                                fast_parser, get_attachments)

login, password = '******', 'password'                                    # be shure to use right
messages = MessagesAPI(login=login, password=password, two_factor=True)  # two_factor auth parametr

peer_id = '123456789' 
history = messages.method('messages.getHistory', offset=1,          # all methods work
                                        user_id=peer_id, count=5)   # as they described in 
print(*[i['text'] for i in history['items']], sep='\n')             # the offical documentation


messages.method('messages.send', user_id=peer_id, message='Hello',     # You can use uploading from
            attachment='photo123456_7891011', random_id=get_random())  # vk_api library on github


attachment_photos = get_attachments(attachment_type='photo', peer_id=peer_id,          # you can use custom
                            offset=1, count=1, cookies_final=messages.get_cookies())   # written methods by
print('\n', len(attachment_photos), sep='\n')                                          # getting auth cookies


authors = get_creators(post='-12345_67890',            # or even get information
                    cookies=messages.get_cookies())    # that is not provided with
print(cleanhtml(authors))                              # offical API
コード例 #7
0
vk_session = vk_api.VkApi(LOGIN,
                          PASSWORD,
                          auth_handler=auth_handler,
                          captcha_handler=captcha_handler)

messages = MessagesAPI(login=LOGIN, password=PASSWORD, two_factor=True)

try:
    vk_session.auth()
except vk_api.AuthError as error_msg:
    print(error_msg)
    quit(-1)

vk = vk_session.get_api()

d = dict(messages.method("messages.getChat", chat_id=CHAT_ID))

if d == {}:
    print("[ERROR] No users found")
    exit(-1)

users_info = vk.users.get(user_ids=d["users"], fields="bdate")
ids = [x["id"] for x in users_info]
first_names = [x["first_name"] for x in users_info]
last_names = [x["last_name"] for x in users_info]
bdates = []

for x in users_info:
    try:
        bdates.append(x["bdate"])
    except:
コード例 #8
0
upload_url = raw["response"]["upload_url"].replace("\/", "/")
print("[INFO] Got upload server...")

print("[INFO] Getting file data...")
response = requests.post(
    upload_url, files={"file": open(args.file.split(".")[0] + ".ogg", "rb")})
raw = response.content.decode("utf-8")
if "error" in raw:
    print("[ERROR] Error while getting file data. Response:")
    print(raw)
    exit(-1)
processed = ast.literal_eval(raw)["file"]
print("[INFO] Got file data...")

print("[INFO] Saving the file...")
processed = messages.method("docs.save", file=processed)
if "error" in processed:
    print("[ERROR] Error while saving the file. Response:")
    print(raw)
    exit(-1)

MEDIA_ID = processed["audio_message"]["id"]
OWNER_ID = processed["audio_message"]["owner_id"]
ATTACHMENT = "doc{}_{}".format(OWNER_ID, MEDIA_ID)
response = messages.method("messages.send",
                           random_id=random.randint(0, 2147483647),
                           peer_id=args.peerID,
                           message=args.message,
                           attachment=ATTACHMENT)
if "error" in raw:
    print("[ERROR] Error while sending the audio. Response:")