Beispiel #1
1
def _init():
    config = configparser.ConfigParser()
    config.read("config.ini")
    hostname = config['DEFAULT']['server']

    server = MinecraftServer.lookup(hostname)
    return server
Beispiel #2
0
def is_online():
    try:
        MinecraftServer.lookup(SERVER_HOSTNAME).ping()

        return True
    except:
        return False
Beispiel #3
0
 async def server(self, ctx, host):
     if(":" not in host):
         server = MinecraftServer.lookup(host + ":25565")
     else:
         server = MinecraftServer.lookup(host)
     statushow = server.status()
     await ctx.send("There are " + str(statushow.players.online) + " people on " + host)
Beispiel #4
0
async def update_status(channel, hostname, sleep_time):
    """
    :param channel: Channel where messages will be written
    :param hostname: IP of the server
    :param sleep_time: Time to wait before update
    :return: Send messages or edit them if they are already sent
    """

    already_send = False
    iterate = 0
    messages = []
    while True:
        # Using mcstatus module to get servers infos easily
        response = MinecraftServer.lookup(f'{hostname}')
        query = response.query()
        status = response.status()
        display_announcement: str = "Les serveurs Odyssia sont **accessibles à tous** !"
        display_players: str = f"Joueurs actuellement en ligne ({status.players.online}) " + (
            ": {0}".format(", ".join(query.players.names)))
        display_status: str = "Le serveur {0} est **Ouvert**"
        separator: str = "======================"
        if already_send is False:
            # Send messages once
            await channel.send(display_announcement)
            await channel.send(separator)
            players_online = await channel.send(display_players)
            await channel.send(separator)
        else:
            # The message is edited the rest of the time, because it is already written
            await players_online.edit(content=display_players)
        for server_name, port in ports.items():
            try:
                response = MinecraftServer.lookup(f'{hostname}:{port}')
                status = response.status()
                if already_send is False:
                    # Send the message once
                    status_message = await channel.send(
                        display_status.format(server_name,
                                              status.players.online))
                    messages.append(status_message)
                else:
                    # The message is edited the rest of the time, because it is already written
                    await messages[iterate].edit(content=display_status.format(
                        server_name, status.players.online))
            except (ConnectionRefusedError, AttributeError, Exception):
                await messages[iterate].edit(
                    content="Le serveur {0} est **Fermé**".format(
                        server_name, status.players.online))
            iterate += 1
            # Wait until the next update
        await asyncio.sleep(sleep_time)
        # All messages have been sent one time, so we don't want to rewrite them, but just editing them
        already_send = True
        iterate = 0
Beispiel #5
0
	async def start(self,ctx:SlashContext,server:str):
		if serverStarted: return
		try: os.chdir(servers([server,'directory']))
		except: await ctx.send('server name error')
		os.startfile('botStart.bat')
		os.chdir(mainDirectory)
		await ctx.send('okay, it\'s starting.')
		for i in range(save.read(['servers',str(ctx.guild.id),'config','maxServerStartTime'])):
			try: MinecraftServer.lookup(serverQuery).query().players.online; break
			except: asyncio.sleep(1)
		else: await ctx.send('error starting server.'); return
		await ctx.send('it should be up.')
		logOutput(f'starting server {server}',ctx)
Beispiel #6
0
 def ping():
     self.__info_buffer['online'] = ''
     self.__info_buffer['max'] = ''
     self.__info_buffer['version'] = ''
     self.__info_buffer['protocol'] = ''
     self.__info_buffer['players'] = ''
     self.__info_buffer['ping'] = ''
     self.__info_buffer['description'] = ''
     self.__info_buffer['map'] = ''
     self.__info_buffer['brand'] = ''
     self.__info_buffer['plugins'] = ''
     config = self.main.widget_manager.config.config
     if 'servers' not in config[self.main.info.NAME]:
         return
     servers = json.loads(config[self.main.info.NAME]['servers'])
     if not servers:
         return
     addr = servers[self.main.list.currentRow()]
     try:
         status = MinecraftServer.lookup(addr).status()
     except:
         print_stack_trace(LogLevel.DEBUG)()
         return
     self.__info_buffer['online'] = str(status.players.online)
     self.__info_buffer['max'] = str(status.players.max)
     self.__info_buffer['version'] = status.version.name
     self.__info_buffer['protocol'] = status.version.protocol
     self.__info_buffer['ping'] = str(status.latency)
     players = ''
     if status.players.sample:
         for p in status.players.sample:
             players += p.name + '(' + p.id + ')' + ', <br/>'
     self.__info_buffer['players'] = players[:-7]
     self.__info_buffer['description'] = get_description(
         status.description)
     try:
         query = MinecraftServer.lookup(addr).query()
     except:
         print_stack_trace(LogLevel.DEBUG)()
         return
     self.__info_buffer['map'] = query.map
     self.__info_buffer['brand'] = query.software.brand
     plugins = ''
     for p in query.software.plugins:
         plugins += p + ', '
     self.__info_buffer['plugins'] = plugins[:-2]
     for p in query.players.names:
         if p not in players:
             players += p + ', <br/>'
     self.__info_buffer['players'] = players[:-7]
Beispiel #7
0
async def get_mcstatus(addr: str) -> Optional[Message]:
    try:
        server = MinecraftServer.lookup(addr)
        status = await server.async_status()
        version = status.version.name
        protocol = status.version.protocol
        players_online = status.players.online
        players_max = status.players.max
        players = status.players.sample
        player_names = [player.name for player in players] if players else []
        description = status.description
        latency = status.latency
        favicon = status.favicon
    except:
        logger.warning(traceback.format_exc())
        return None

    msg = Message()
    if favicon:
        msg.append(
            MessageSegment.image(
                "base64://" + favicon.replace("data:image/png;base64,", "")
            )
        )
    msg.append(
        f"服务端版本:{version}\n"
        f"协议版本:{protocol}\n"
        f"当前人数:{players_online}/{players_max}\n"
        f"在线玩家:{'、'.join(player_names)}\n"
        f"描述文本:{description}\n"
        f"游戏延迟:{latency}ms"
    )
    return msg
def mcping(text):
    """<server[:port]> - gets info about the Minecraft server at <server[:port]>"""
    try:
        server = MinecraftServer.lookup(text)
    except (IOError, ValueError) as e:
        return str(e)

    try:
        s = server.status()  # type: PingResponse
    except socket.gaierror:
        return "Invalid hostname"
    except socket.timeout:
        return "Request timed out"
    except ConnectionRefusedError:
        return "Connection refused"
    except ConnectionError:
        return "Connection error"
    except (IOError, ValueError) as e:
        return "Error pinging server: {}".format(e)

    if isinstance(s.description, dict):
        description = format_colors(" ".join(s.description["text"].split()))
    else:
        description = format_colors(" ".join(s.description.split()))

    output_format = colors.parse(
        "{}$(clear) - $(bold){}$(clear) - $(bold){:.1f}ms$(clear) - $(bold){}/{}$(clear) players"
    )

    return output_format.format(
        description, s.version.name, s.latency, s.players.online, s.players.max
    ).replace("\n", colors.parse("$(clear) - "))
Beispiel #9
0
def index(request):		
	# Get the server
	server = MinecraftServer.lookup("www.yourServerHere.com:25565")

	# Get the status and query data, requires two calls to get everything.
	status = server.status()
	query = server.query()

	# Create the object to store all the server data.
	req = {}
		
	req['playerCount'] = status.players.online
	req['maxPlayers'] = status.players.max

	req['playerNames'] = query.players.names
	
	req['version'] = query.software.version;
	req['motd'] = query.motd;
	req['map'] = query.map;

	# Package the requested data into the callback for JSONP
	callback = request.GET.get('callback', '')
	response = json.dumps(req)
	response = callback + '(' + response + ');'

	return HttpResponse(response, content_type="application/json")
Beispiel #10
0
async def update_servers():
    servers.clear()
    for key in config.c['SERVERS']:
        servers[key] = {'obj': MinecraftServer.lookup(config.c['SERVERS'][key]), 'players': None, "online": None,
                        'message': await get_message(key)}

    print(f"Connected to {', '.join([servers[x]['obj'].host for x in servers])}")
Beispiel #11
0
    async def server_info(ctx):
        try:
            server = MinecraftServer.lookup("147.135.71.70:25592")
            if server.status() is None:
                description = f"IP : `147.135.71.70:25592`\n"
                line = "âš«"
            else:
                mc_status = server.status()
                description = f"**IP :** `147.135.71.70:25592`\n" \
                              f"**Version :** {mc_status.version.name}\n" \
                              f"**Latency :** {mc_status.latency}\n" \
                              f"**Players :** {mc_status.players.online}/{mc_status.players.max}\n"
                line = "🟢"

                # Fetching players names
                try:
                    description += '\n'.join([f" \> {x.name}" for x in mc_status.players.sample])
                except Exception as e:
                    print(e)

            final = discord.Embed(title=f"{line}  **FailureSMP**",
                                  description=description,
                                  color=Formatting.colour())
        except:
            final = discord.Embed(title="_FailureSMP cannot be pinged at the moment._",
                                  description="Please try again in the near future.")
        await ctx.send(embed=final)
Beispiel #12
0
 async def mcplayers(self, ctx, host: str, port: int = 25565):
     await self.bot.delete_message(ctx.message)
     server = MinecraftServer.lookup(host, port)
     query = server.query()
     await self.bot.say(
         "The server has the following players online: {0}".format(
             ", ".join(query.players.names)))
def json_server_info():
    server_name = request.args.get("server_name")
    if server_name:
        try:
            mcserver = MinecraftServer.lookup(server_name)
            server_status = mcserver.status()
            if server_status.players.sample:
                sample = [{
                    "name": p.name,
                    "id": p.id
                } for p in server_status.players.sample]
            else:
                sample = []
            json_status = {
                "name": server_name,
                "description": server_status.description,
                "players": {
                    "online": server_status.players.online,
                    "max": server_status.players.max,
                    "sample": sample
                },
                "favicon": server_status.favicon,
                "version": {
                    "name": server_status.version.name,
                    "protocol": server_status.version.protocol
                },
                "latency": server_status.latency
            }
            if server_name not in recent_searches:
                recent_searches.append(server_name)
        except socket.gaierror:
            return jsonify(message="server not found")
        except socket.timeout:
            return jsonify(message="socket timed out")
        return jsonify(json_status)
Beispiel #14
0
async def dj(ctx):  #dj command
    await ctx.send("Fetching server info, please wait..."
                   )  #sends pls wait message in discord
    server = MinecraftServer.lookup(
        "minecraft.digitaljesuit.com:25565")  #pings Dj

    status = server.status()  #gets dj info

    embed = discord.Embed(
        title="Digital Jesuit",
        description="Info about Digital Jesuit",
        colour=discord.colour.Color.blue())  #creates an embed with dj info
    embed.set_author(name="Red Tech™ Bot", icon_url=rtFuncs.rtlogo)
    embed.set_thumbnail(
        url=
        "https://cdn.discordapp.com/icons/546412536522735629/dde78cbf87e204472d40b416df64cfbd.png?size=2048"
    )
    embed.add_field(name="Players Online",
                    value=status.players.online,
                    inline=True)
    embed.add_field(name="Ping", value=status.latency, inline=True)
    embed.add_field(name="Server Address",
                    value="minecraft.digitaljesuit.com",
                    inline=True)
    embed.add_field(name="Server Invite Link:",
                    value=jonFuncs.djDisc(),
                    inline=False)
    await ctx.send(embed=embed)  #sends embed
Beispiel #15
0
    def __init__(self, bot: Bot) -> None:
        self.bot = bot
        self.server = MinecraftServer.lookup(Minecraft.server_address)
        self.gurkcraft: Optional[TextChannel] = None
        self.gurkcraft_relay: Optional[TextChannel] = None

        self.update_channel_description.start()
def mcping(text):
    """<server[:port]> - gets info about the Minecraft server at <server[:port]>"""
    try:
        server = MinecraftServer.lookup(text)
    except (IOError, ValueError) as e:
        return e

    try:
        s = server.status()
    except socket.gaierror:
        return "Invalid hostname"
    except socket.timeout:
        return "Request timed out"
    except ConnectionRefusedError:
        return "Connection refused"
    except ConnectionError:
        return "Connection error"
    except (IOError, ValueError) as e:
        return "Error pinging server: {}".format(e)

    if isinstance(s.description, dict):
        description = format_colors(" ".join(s.description["text"].split()))
    else:
        description = format_colors(" ".join(s.description.split()))

    if s.latency:
        return "{}\x0f - \x02{}\x0f - \x02{:.1f}ms\x02" " - \x02{}/{}\x02 players".format(
            description, s.version.name, s.latency, s.players.online, s.players.max
        ).replace("\n", "\x0f - ")
    else:
        return "{}\x0f - \x02{}\x0f" " - \x02{}/{}\x02 players".format(
            description, s.version.name, s.players.online, s.players.max
        ).replace("\n", "\x0f - ")
Beispiel #17
0
 async def mcping(self, ctx, host: str, port: int = 25565):
     await self.bot.delete_message(ctx.message)
     server = MinecraftServer.lookup(host, port)
     status = server.status()
     await self.bot.say(
         "The server has {0} players and replied in {1} ms".format(
             status.players.online, status.latency))
Beispiel #18
0
async def server(ctx):

    server = MinecraftServer.lookup('(remove parentheses and put ip here)')
    status = server.status()

    await ctx.send("The server has {0} players and replied in {1} ms".format(
        status.players.online, status.latency))
Beispiel #19
0
 async def mc_ping(self, ctx, *, server: str):
     await ctx.trigger_typing()
     server = server.replace(" ", "")
     if ":" in server:
         s = server.split(":")
         try:
             int(s[1])
         except Exception:
             await ctx.send(embed=discord.Embed(
                 color=discord.Color.green(),
                 description="**" + server +
                 "** is either offline or unavailable at the moment.\n" +
                 "Did you type the ip and port correctly? (Like ip:port)\n\nExample: ``"
                 + ctx.prefix + "mcping 172.10.17.177:25565``"))
             return
     if server == "":
         await ctx.send(embed=discord.Embed(
             color=discord.Color.green(),
             description="You must specify a server to ping!"))
         return
     status = MinecraftServer.lookup(server)
     try:
         status = status.status()
         await ctx.send(embed=discord.Embed(
             color=discord.Color.green(),
             description=server +
             " is online with {0} player(s) and a ping of {1} ms.".format(
                 status.players.online, status.latency)))
     except Exception:
         await ctx.send(embed=discord.Embed(
             color=discord.Color.green(),
             description="**" + server +
             "** is either offline or unavailable at the moment.\n" +
             "Did you type the ip and port correctly? (Like ip:port)\n\nExample: ``"
             + ctx.prefix + "mcping 172.10.17.177:25565``"))
Beispiel #20
0
    def query_command(self, protocol, caller, source, command, raw_args,
                      parsed_args):
        if len(parsed_args) < 1:
            caller.respond("Usage: {CHARS}mcquery <address[:port]>")
        address = parsed_args[0]
        target = source

        if isinstance(source, User):
            target = caller

        try:
            q = MinecraftServer.lookup(address)
            status = q.status()
        except Exception as e:
            target.respond("Error retrieving status: %s" % e)
            self.logger.exception("Error retrieving status")
            return

        servername = status.description

        if isinstance(servername, dict):
            servername = servername.get("text", "<Unknown server name>")

        done = ""
        done += "[%s] %s | " % (status.version.name, servername)
        done += "%s/%s " % (status.players.online, status.players.max)
        if "plugins" in status.raw:
            done += "| %s plugins" % len(status.raw["plugins"])

        target.respond(done)

        if protocol.can_flood and status.players.sample:
            players = ", ".join([x.name for x in status.players.sample])
            target.respond("Players: %s" % players)
Beispiel #21
0
    def standard_je_ping(self, combined_server):
        try:
            status = MinecraftServer.lookup(combined_server).status()
        except Exception:
            return False, 0, None

        return True, status.players.online, status.latency
Beispiel #22
0
def check_minecraft_status(ip):
    if ip != '':
        try:
            server = MinecraftServer.lookup(ip)
            status = server.status()
            # print(status)
            # print("The server has {0} players and replied in {1} ms".format(status.players.online, status.latency))
            # print(status.version.name, status.description)

            query = server.query()
            # print(query.motd, query.software.plugins, query.players.names, query.software.version)
            # print("The server has the following players online: {0}".format(", ".join(query.players.names)))

            return {
                'Num Players': status.players.online,
                'Players': ", ".join(query.players.names),
                'Motd': query.motd,
                'Version': status.version.name,
                'Description': status.description['text'],
                'Latency': '{}ms'.format(status.latency)
            }

        except Exception as e:
            print("Error while checking for minecraft status", e)

    return {}
Beispiel #23
0
def mcb():

    # Look up server
    server = MinecraftServer.lookup('98.244.54.58:25565')
    ip = '{}:{}'.format(server.host, server.port)

    # Ping the server
    stat = None
    rawinfo = None
    players = None
    try:
        ping = server.ping()
    except Exception as e:
        return 'Server is down :('
    else:
        stat = 1

    if stat == 1:
        # Get query info
        rawinfo = server.query().raw
        players = server.query().players.names

    return render_template('mcb.html',
                           stat=stat,
                           pnum=int(rawinfo['numplayers']),
                           names=players,
                           ver=rawinfo['version'],
                           ip=ip)
Beispiel #24
0
def index():
    version = 'N/A'
    max_number = 'null'
    current = 'null'
    players = []

    server = MinecraftServer.lookup(os.getenv("MC_SERVER_HOST"))

    new_loop = asyncio.new_event_loop()  # 非主程序無法直接 get_event_loop, 所以 new 一個
    asyncio.set_event_loop(new_loop)
    loop = asyncio.get_event_loop()

    status = request_server_info(loop, server.status)
    if status is not None:
        version = status.version.name
        max_number = status.players.max
        current = status.players.online

    query = request_server_info(loop, server.query)
    if query is not None:
        players = query.players.names

    return render_template('main.html',
                           version=version,
                           max_number=max_number,
                           current=current,
                           players=players)
Beispiel #25
0
    async def __call__(self, scope, receive, send):
        assert scope['type'] == 'http'

        if scope['path'] == "/status":
            await send(self.get_pre_send_dict_ok())
            await send(self.get_send_dict(
                self.status_repo.get_data()
            ))
        elif scope['path'] == '/stats':
            await send(self.get_pre_send_dict_ok())
            await send(self.get_send_dict(
                self.stats_repo.get_data()
            ))
        elif scope['path'] == "/":
            server = MinecraftServer.lookup(
                f"{self.server_hostname}:{self.server_port}"
            )
            status = server.status()
            to_return = {
                'version': status.version.name,
                'players_online': status.players.online,
                'players_max': status.players.max
            }
            await send(self.get_pre_send_dict_ok())
            await send(self.get_send_dict(to_return))
        else:
            await send(self.get_pre_send_dict_404())
            await send(self.get_send_dict({'message': "Not found"}))
Beispiel #26
0
def status(bot, trigger):
    """
    .status <server> - Grabs information about a minecraft server!
    """
    try:
        server = MinecraftServer.lookup(trigger.group(3).strip())
    except Exception:
        bot.say(u'[MCS] Unable to find a Minecraft server running at \'{}\''.
                format(trigger.group(3).strip()))

    try:
        status = server.status()
        desc = ' '.join(re.sub(u'\u00A7.', '', status.description).split())
        bot.say(u'[MCS] {0} | {1} players | {2} ms | {3}'.format(
            trigger.group(3).strip(), status.players.online, status.latency,
            desc))
    except Exception as e:
        try:
            raw = web.get('http://minespy.net/api/serverping/' +
                          str(server.host) + ':' + str(server.port))
            status = json.loads(raw)
            bot.say(u'[MCS] {0} | {1} players | {2} ms | {3}'.format(
                trigger.group(3).strip(), str(status['online']),
                str(status['latency']), str(status['strippedmotd'])))
        except Exception as e:
            bot.say(u'[MCS] Unable to fetch info from \'{}\' ({})'.format(
                trigger.group(3).strip(), e))
Beispiel #27
0
def ping_status(combined_server):  # all je servers support this
    try:
        status = mcstatus.lookup(combined_server).status()
    except Exception:
        return default

    s_dict = default.copy()

    s_dict['online'] = True
    s_dict['players_online'] = status.players.online
    s_dict['players_max'] = status.players.max
    s_dict['players_names'] = None if status.players.sample is None else [
        p.name for p in status.players.sample
    ]
    s_dict['latency'] = round(status.latency, 2)
    s_dict['version'] = {
        'brand': 'Java Edition',
        'software': status.version.name,  # string
        'protocol': f'ping {status.version.protocol}',  #string
        'method': 'ping'
    }
    s_dict['motd'] = status.description
    s_dict['favicon'] = status.favicon

    return s_dict
Beispiel #28
0
    def query_command(self, protocol, caller, source, command, raw_args,
                      parsed_args):
        if len(parsed_args) < 1:
            caller.respond("Usage: {CHARS}mcquery <address[:port]>")
        address = parsed_args[0]
        target = source

        if isinstance(source, User):
            target = caller

        try:
            q = MinecraftServer.lookup(address)
            status = q.status()
        except Exception as e:
            target.respond("Error retrieving status: %s" % e)
            self.logger.exception("Error retrieving status")
            return

        servername = status.description

        if isinstance(servername, dict):
            servername = servername.get("text", "<Unknown server name>")

        done = ""
        done += "[%s] %s | " % (status.version.name, servername)
        done += "%s/%s " % (status.players.online, status.players.max)
        if "plugins" in status.raw:
            done += "| %s plugins" % len(status.raw["plugins"])

        target.respond(done)

        if protocol.can_flood and status.players.sample:
            players = ", ".join([x.name for x in status.players.sample])
            target.respond("Players: %s" % players)
Beispiel #29
0
async def ping(request):
    data = {'online': False}
    try:
        server = MinecraftServer.lookup(request.match_info['address'])
        status = server.status()

        data['ping'] = status.latency
        data['online'] = True
        data['players'] = {
            'online': status.players.online,
            'max': status.players.max
        }
        data['protocol'] = status.version.protocol
        data['favicon'] = status.favicon

        # weird motd things.
        motd = status.description
        if "extra" in motd:
            motd = ""
            for key in status.description['extra']:
                if key['color'] is not None:
                    motd = motd + colours[key['color']]
                motd = motd + key['text']
        elif "text" in motd:
            motd = motd['text']

        data['description'] = {'raw': status.description, 'normal': motd}
    except:
        pass
    return web.json_response(data)
Beispiel #30
0
    async def mc(self, ctx):
        """Get the Minecraft server information."""

        server = MinecraftServer.lookup(config.hvc_mc['ip'])

        embed = discord.Embed(
            title='Minecraft Server',
            description='Official Hatventures Community Minecraft server',
            colour=0x5A894D,
            url=None)
        embed.add_field(name='IP', value=config.hvc_mc['ip_name'], inline=True)
        embed.add_field(name='Dynmap',
                        value=config.hvc_mc['dynmap'],
                        inline=True)
        try:
            status = server.status()
            embed.add_field(name='Version',
                            value=status.version.name,
                            inline=True)
            embed.add_field(name='Status', value='Online!', inline=True)
            embed.add_field(name='Players',
                            value='{0.online}/{0.max}'.format(status.players),
                            inline=True)
        except Exception as e:
            print(e)
            embed.add_field(name='Status', value='Offline!')

        embed.set_thumbnail(url=config.hvc_mc['icon'])

        await ctx.send(embed=embed)
Beispiel #31
0
def cmd_status(update, context):
    """Usage: /status url"""
    logging.info("/status called")
    context.bot.send_chat_action(chat_id=update.message.chat_id,
                                 action=telegram.ChatAction.TYPING)

    chat_data = context.chat_data

    try:

        if len(context.args) != 1:
            error_incomplete(context.bot, update)
            logging.info(
                "/status did't provide an url, /status minecraft.example.com",
            )
            return

        if not utils.validUrl(context.args[0]):
            error_url(context.bot, update, context.args)
            logging.info("Invalid URL, too long")
            return

        chat_data['url'] = context.args[0]
        chat_data['server'] = MinecraftServer.lookup(chat_data['url'])
        chat_data['status'] = chat_data['server'].status()

        info_status(context.bot, update.message.chat_id, chat_data['url'],
                    chat_data['status'])
        logging.info("/status %s online" % context.args[0])
    except Exception as e:
        error_status(context.bot, update.message.chat_id, context.args)
        logging.exception(e)
Beispiel #32
0
    async def mcstats(self, ctx, adress: str):
        """Статистика сервера Minecraft.

        Аргументы:
        `:adress` - адрес сервера (домен / IP)
        __                                            __
        Например:
        ```
        n!mcserver hypixel.net
        n!mcstats play.hypixel.net:25565
        ```
        """

        try:
            server = MinecraftServer.lookup(adress)
            status = server.status()
        except ConnectionRefusedError:
            return await ctx.send(':x: Не удалось подключиться к серверу "%s".' % adress)

        embed = discord.Embed(timestamp=ctx.message.created_at, color=0x18C30B, description="```%s```" % ''.join([x['text'] for x in status.description['extra']]))

        try:
            embed.add_field(name='Адрес', value=server.host)
            embed.add_field(name='Порт', value=server.port)
            embed.add_field(name='Игроки', value='%s/%s' % (status.players.online, status.players.max))
            embed.add_field(name='Задержка', value='%s мс' % status.latency)
            embed.add_field(name='Ядро', value=status.version.name)
        except:
            embed.add_field(name='Что-то пошло не так', value='Попробуйте ввести адрес **существующего** сервера.')

        await ctx.send(embed=embed)
Beispiel #33
0
def query_status(
        combined_server):  # some je and most pocketmine servers support this
    time_before = time()

    try:
        query = mcstatus.lookup(combined_server).query()
    except Exception:
        return default

    latency = round((time() - time_before) * 1000, 2)

    s_dict = default.copy()

    s_dict['online'] = True
    s_dict['players_online'] = query.players.online
    s_dict['players_max'] = query.players.max
    s_dict['players_names'] = query.players.names
    s_dict['latency'] = latency
    s_dict['version'] = {
        'brand': None,
        'software': query.software.version,  # string
        'protocol': 'query',
        'method': 'query'
    }
    s_dict['motd'] = query.motd
    s_dict['map'] = query.map
    s_dict['plugins'] = query.software.plugins

    return s_dict
Beispiel #34
0
def refresh():
    threading.Timer(20, refresh).start()  #refreshes every 10 seconds
    server = MinecraftServer.lookup("SERVER_IP")
    query = server.query()
    #list of names all online players
    currentServerPlayers = query.players.names
    hasChanged = False  #did the citizenslist change?
    for citizen in townlist:
        #if citizen is on serverlist but not on townlist, add them to townlist
        if citizen in currentServerPlayers:
            if citizen not in currentTownPlayers:
                currentTownPlayers.append(citizen)
                hasChanged = True
        #if citizen is not on serverlist but on townlist, remove them from
        #townlist
        if citizen not in currentServerPlayers:
            if citizen in currentTownPlayers:
                currentTownPlayers.remove(citizen)
                hasChanged = True
    if (hasChanged):
        if (currentTownPlayers.__len__ == 0):
            #use client.uid instead of friend.uid to msg self
            client.sendMessage('Current players in Server: n/a',
                               thread_id=friend.uid)
        else:
            #use client.uid instead of friend.uid to msg self
            client.sendMessage("Current players in Server: " +
                               ", ".join(currentTownPlayers),
                               thread_id=friend.uid)
    print('refreshed')
Beispiel #35
0
 def getStatus(self):
     prop = self.getProperties()
     port = prop["server-port"]
     host = prop["server-ip"]
     if not host:
         host = "127.0.0.1"
     print(port, host)
     return MinecraftServer.lookup(host + ":" + port).status()
Beispiel #36
0
def minecraft_test(server_info, extra):
    try:
        server = MinecraftServer.lookup(server_info)
        server.status()
        return True
    except Exception as e:
        print e
        return False
Beispiel #37
0
def minecraft_status (bot, msg):
    server = MinecraftServer.lookup("minecraft.westsixth.net:25565")
    query = server.query()
    if not query.players.names:
         bot.say(msg.channel, "Nobody is on :-(")
         bot.say(msg.channel, "The server is running version {0} at the moment.".format("".join(query.software.version)))
    else:
        bot.say(msg.channel, "The following people are on: {0}".format(", ".join(query.players.names)))
        bot.say(msg.channel, "The server is running version {0} at the moment.".format("".join(query.software.version)))
Beispiel #38
0
def query_server(server):
    """Query the minecraft server"""
    server = MinecraftServer.lookup(server)
    try:
        response = server.query()
    except socket.timeout:
      return None
    else:
      return response
Beispiel #39
0
    async def __call__(self, client, message):
        ip = message.content.split(' ')[1]

        server = MinecraftServer.lookup(ip)
        try:
            status = server.status()
            await client.send_message(message.channel, '**{0}**: {1} players online. Running {2}'.format(
                      ip, status.players.online, status.version.name))
        except socket.gaierror:
            await client.send_message(message.channel, 'Cannot reach server.')
Beispiel #40
0
def get_players(address):
    if not address:
        return []
    print "Connecting to {}".format(address)
    server = MinecraftServer.lookup(address)
    resp = server.status()
    try:
        return [p.name for p in resp.players.sample]
    except TypeError:
        return []
Beispiel #41
0
def index(request):
    try:
        server = MinecraftServer.lookup(settings.MC_HOST)
        status = server.status()
        query = server.query()
    except:
        status = None
        query = None
    user = Account.objects.all()
    top_m = Fe.objects.order_by("-money").exclude(name__contains="-")
    return render(request, "portal/index.html", {"status": status, "query": query, "top_m": top_m, "user": user})
Beispiel #42
0
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type','text/html')
        self.end_headers()
	if self.path.translate(None, "/") in Config.keys():
	    server = MinecraftServer.lookup(Config[self.path.translate(None, "/")])
	    status = server.status()
	    result = {'online': status.players.online, 'latency': status.latency}
	    self.wfile.write(json.dumps(result))
	else:
	    self.wfile.write("Failed")
    def check(self, textkey, data, config):
        server = MinecraftServer.lookup("localhost:25565")
        srv = server.status()
        players = srv.players.online
        latency = server.ping()

        if textkey == 'players': 
            return players

	elif textkey == 'latency':
            return latency

        return 0
Beispiel #44
0
 def updateOnlineServers(self):
     connection = sqlite3.connect("servers.db")
     cursor = connection.cursor()
     ports = AnalyzeData.getPorts()
     for x in ports:
         name="node" + str(x)
         try:
             server = MinecraftServer.lookup("127.0.0.1:" + str(x))
             status = server.ping()
         except timeout:
             cursor.execute("UPDATE server_running SET running=? WHERE name=?", (False,name))
             connection.commit()
     connection.close()
Beispiel #45
0
def status(bot, trigger):
    """
    .status <server> - Grabs information about a minecraft server!
    """
    try:
        server = MinecraftServer.lookup(trigger.group(3).strip())
    except Exception:
        bot.say(u'[MCS] Unable to find a Minecraft server running at \'{}\''.format(trigger.group(3).strip()))

    try:
        status = server.status()
        desc = ' '.join(re.sub(u'\u00A7.', '', status.description).split())
        bot.say(u'[MCS] {0} | {1} players | {2} ms | {3}'.format(trigger.group(3).strip(), status.players.online, status.latency, desc))
    except Exception as e:
        bot.say(u'[MCS] Unable to fetch info from \'{}\' ({})'.format(trigger.group(3).strip(), e))
Beispiel #46
0
def index():
    # Server IPs

    lobby_ip = '50.116.56.173:25565'

    # Fetch Server Data

    server = MinecraftServer.lookup(lobby_ip)
    status = server.status()
#   latency = server.ping()
#   query = server.query()

    lobby_players = status.players.online

    return render_template("index.html", count=lobby_players)
def check_status():
    global bad_latency_time, last_bad_latency_time, offline_time, last_offline_time, latency

    try:
        server = MinecraftServer.lookup(SERVER_IP)
        status = server.status()
        print("Server Latency: " + str(status.latency))
        latency = status.latency
        offline_time = None
        if latency < MAX_LATENCY:
            bad_latency_time = None
        elif bad_latency_time is None:
            bad_latency_time = int(round(time.time() * 100))
    except Exception:
        print("Server Offline")
        if offline_time is None:
            offline_time = int(round(time.time() * 100))
Beispiel #48
0
 def __init__(self, name, initialize = False):
     self.id = config["Servers"][name]["ID"]
     self.name = name
     self.minRam = config["Servers"][name]["MinRAM"]
     self.maxRam = config["Servers"][name]["MaxRAM"]
     self.fileName = config["Servers"][name]["FileName"]
     self.directory = config["Servers"][name]["Directory"]
     self.stopCommands = config["Servers"][name]["StopCommands"]
     self.description = config["Servers"][name]["Description"]
     self.serverIp = config["Servers"][name]["IP"]
     self.port = config["Servers"][name]["Port"]
     self.runningInfo = serverStatus.lookup("{0}:{1}".format(self.serverIp,self.port))
     if initialize:
         self._initialize()
         if not self.checkRunning(2):
             raise DsmmError("Unable to initialize")
     else:
         self.screen = Screen(self.name)
     return
def status(hostname, port=25565):
	server = MinecraftServer.lookup("{0}:{1}".format(hostname, port))
	status = server.status()
	ping = server.ping()
	players = []

	if status.players.sample != None:
		players = [p.name for p in status.players.sample]

	return jsonify (
		hostname=hostname,
		port=port,
		description=status.description,
		version=status.version.name,
		players_online=status.players.online,
		players_max=status.players.max,
		players=','.join(players),
		ping=ping
	)
Beispiel #50
0
def status(bot, trigger):
    """
    .status <server> - Grabs information about a minecraft server!
    """
    try:
        server = MinecraftServer.lookup(trigger.group(3).strip())
    except Exception:
        bot.say(u'[MCS] Unable to find a Minecraft server running at \'{}\''.format(trigger.group(3).strip()))

    try:
        status = server.status()
        desc = ' '.join(re.sub(u'\u00A7.', '', status.description).split())
        bot.say(u'[MCS] {0} | {1} players | {2} ms | {3}'.format(trigger.group(3).strip(), status.players.online, status.latency, desc))
    except Exception as e:
        try:
            raw = web.get('http://minespy.net/api/serverping/' + str(server.host) + ':' + str(server.port))
            status = json.loads(raw)
            bot.say(u'[MCS] {0} | {1} players | {2} ms | {3}'.format(trigger.group(3).strip(), str(status['online']), str(status['latency']), str(status['strippedmotd'])))
        except Exception as e:
            bot.say(u'[MCS] Unable to fetch info from \'{}\' ({})'.format(trigger.group(3).strip(), e))
def players():
    server_info = "52.207.3.215:25565"
    data = {}

    data["server"] = server_info
    # If you know the host and port, you may skip this and use MinecraftServer("example.org", 1234)
    try:
        server = MinecraftServer.lookup(server_info)
        status = server.status()

    except Exception as e:
        print e
        data["error"] = str(e)
        return jsonify(data)


    # 'status' is supported by all Minecraft servers that are version 1.7 or higher.
    print "status",server.status()
    data["status.latency.ms"] = status.latency
    data["currently_online"] = status.players.online

    print("The server has {0} players and replied in {1} ms".format(status.players.online, status.latency))
    if status.players.online > 0:
        print status.players.stu[u'sample']
        data["players"] = []
        for p in status.players.stu[u'sample']:
            data["players"].append(p[u'name'])
        print "data",data
        # 'ping' is supported by all Minecraft servers that are version 1.7 or higher.
        # It is included in a 'status' call, but is exposed separate if you do not require the additional info.
    
    latency = server.ping()
    data["server.latency.ms"] = str(latency)
    print("The server replied in {0} ms".format(latency))

    # 'query' has to be enabled in a servers' server.properties file.
    # It may give more information than a ping, such as a full player list or mod information.
    # query = server.query()
    # print("The server has the following players online: {0}".format(", ".join(query.players.names)))

    return jsonify(data)
Beispiel #52
0
def mcping(text, notice, nick):
    """<server[:port]> - gets info about the Minecraft server at <server[:port]>"""
    if getTokens(nick) < 100:
        notice("You don't have enough tokens to do a mcping... Help a little more !")
        return None
    else:
        takeTokens(10, nick, notice)

    try:
        server = MinecraftServer.lookup(text)
    except (IOError, ValueError) as e:
        return e

    try:
        s = server.status()
    except socket.gaierror:
        return "Invalid hostname"
    except socket.timeout:
        return "Request timed out"
    except ConnectionRefusedError:
        return "Connection refused"
    except ConnectionError:
        return "Connection error"
    except (IOError, ValueError) as e:
        return "Error pinging server: {}".format(e)

    if isinstance(s.description, dict):
        description = format_colors(" ".join(s.description["text"].split()))
    else:
        description = format_colors(" ".join(s.description.split()))

    if s.latency:
        return "{}\x0f - \x02{}\x0f - \x02{:.1f}ms\x02" \
               " - \x02{}/{}\x02 players".format(description, s.version.name_clean, s.latency,
                                                 s.players.online, s.players.max).replace("\n", "\x0f - ")
    else:
        return "{}\x0f - \x02{}\x0f" \
               " - \x02{}/{}\x02 players".format(description, s.version.name_clean,
                                                 s.players.online, s.players.max).replace("\n", "\x0f - ")
Beispiel #53
0
    def check_server(self, addr):
        mc_server = MinecraftServer.lookup(addr)
        query = None
        status = None

        try:
            query = mc_server.query()
        except socket.timeout:
            try:
                status = mc_server.status()
            except socket.timeout:
                print("Cannot reach server {}".format(addr))
            except ConnectionRefusedError:
                print("Connection refused")
        except ConnectionRefusedError:
            print("Connection refused")

        if query is not None:
            return query
        elif status is not None:
            return status
        else:
            return None
Beispiel #54
0
    async def minecraft_ip(self, ip: str):
        # TODO add a check to see if the server is modded
        try:
            server = MinecraftServer.lookup(ip)
            status = server.status()
            data = status.raw
            # print(data)
            ver = data['version']['name']
            version = float(ver[2:])
            if version >= 9:
                s_desc = data['description']['text']
            else:
                s_desc = data['description']
            players = ""
            try:
                for player in data['players']['sample']:
                    players += "{}, ".format(player['name'])
                players = players[:-2]  # Remove final comma and the space after it
            except Exception:
                players = "None"

            # TODO formatting
            msg = """ __*Status of {}*__

Version: {}
Online Players: {}
Description: {}
            """.format(ip, ver, players, s_desc)
            await self.bot.say(msg)

        except ValueError as e:
            await self.bot.say("Invalid IP")
            log.warn(e)

        except Exception as e:
            await self.bot.say("An error has occurred.")
            log.warning("Exception in games.py - {}".format(e))
def echo(bot, update_id, keyConfig):

    # Request updates after the last update_id
    for update in bot.getUpdates(offset=update_id, timeout=10):
        # chat_id is required to reply to any message
        chat_id = update.message.chat_id
        update_id = update.update_id + 1
        message = update.message.text

        if message:
            mcType = message.lower() == '/mcstatus'  # Minecraft Server Status Command
            splitText = message.split(' ', 1)
            if len(splitText) <= 1 and not mcType:
                continue

            wType = splitText[0].lower() == '/getweather'  # Get Weather Command
            xType = splitText[0].lower() == '/getxxx'  # Get P**n Command
            imageType = splitText[0].lower() == '/get'  # Fetch Random Picture Command
            gifType = splitText[0].lower() == '/getgif'  # Fetch GIF Command
            hugeType = splitText[0].lower() == '/gethuge'  # Fetch Large Picture Command
            vidType = splitText[0].lower() == '/getvid'  # Get Top Youtube Result Command
            hugeGifType = splitText[0].lower() == '/gethugegif'  # Fetch Large GIF Command
            dicType = splitText[0].lower() == '/define'  # Command To Define A Word
            urbanDicType = splitText[0].lower() == '/urban'  # Urban Dictionary Command
            placeType = splitText[0].lower() == '/place'  # Google Map Command
            translateType = splitText[0].lower() == '/translate'  # Google translate

            if not mcType:
                requestText = splitText[1]  # imagetext is input text

            if imageType:  # Image Search - GCSE API
                googurl = 'https://www.googleapis.com/customsearch/v1?&searchType=image&num=10&safe=off&' \
                 'cx=' + keyConfig.get('Google', 'GCSE_SE_ID') + '&key=' + keyConfig.get('Google', 'GCSE_APP_ID') + '&q='
                realUrl = googurl + requestText.encode('utf-8')
                data = json.load(urllib.urlopen(realUrl))
                if data['searchInformation']['totalResults'] >= '1':
                    imagelink = data['items'][random.randint(0, 9)]['link']
                    bot.sendChatAction(chat_id=chat_id, action=telegram.ChatAction.UPLOAD_PHOTO)
                    bot.sendPhoto(chat_id=chat_id, photo=imagelink, caption=requestText + ('' if len(imagelink) > 100 else ': ' + imagelink))
                else:
                    bot.sendMessage(chat_id=chat_id, text='I\'m sorry Dave, I\'m afraid I can\'t do that.\n(Image not found)')

            elif gifType:  # GIF Search - GCSE API
                googurl = 'https://www.googleapis.com/customsearch/v1?&searchType=image&num=10&safe=off&' \
                 'cx=' + keyConfig.get('Google', 'GCSE_SE_ID') + '&key=' + keyConfig.get('Google', 'GCSE_APP_ID') + '&q='
                realUrl = googurl + requestText.encode('utf-8') + "&fileType=gif"
                data = json.load(urllib.urlopen(realUrl))
                if data['searchInformation']['totalResults'] >= '1':
                    imagelink = data['items'][random.randint(0, 9)]['link']
                    bot.sendChatAction(chat_id=chat_id, action=telegram.ChatAction.UPLOAD_PHOTO)
                    bot.sendDocument(chat_id=chat_id, filename=requestText + ': ' + imagelink, document=imagelink)
                else:
                    bot.sendMessage(chat_id=chat_id, text='I\'m sorry Dave, I\'m afraid I can\'t do that.\n(Gif not found)')

            elif hugeType:  # Large Image Search - GCSE API
                googurl = 'https://www.googleapis.com/customsearch/v1?&searchType=image&num=10&safe=off&' \
                 'cx=' + keyConfig.get('Google', 'GCSE_SE_ID') + '&key=' + keyConfig.get('Google', 'GCSE_APP_ID') + '&q='
                realUrl = googurl + requestText.encode('utf-8') + "&imgSize=huge"
                data = json.load(urllib.urlopen(realUrl))
                if data['searchInformation']['totalResults'] >= '1':
                    imagelink = data['items'][random.randint(0, 9)]['link']
                    bot.sendChatAction(chat_id=chat_id, action=telegram.ChatAction.UPLOAD_PHOTO)
                    bot.sendPhoto(chat_id=chat_id, photo=imagelink, caption=requestText + ('' if len(imagelink) > 100 else ': ' + imagelink))
                else:
                    bot.sendMessage(chat_id=chat_id, text='I\'m sorry Dave, I\'m afraid I can\'t do that.\n(Image not found)')

            elif hugeGifType:  # Large GIF Search - GCSE API
                googurl = 'https://www.googleapis.com/customsearch/v1?&searchType=image&num=10&safe=off&' \
                 'cx=' + keyConfig.get('Google', 'GCSE_SE_ID') + '&key=' + keyConfig.get('Google', 'GCSE_APP_ID') + '&q='
                realUrl = googurl + requestText.encode('utf-8') + "&imgSize=xlarge" + "&fileType=gif"
                data = json.load(urllib.urlopen(realUrl))
                if data['searchInformation']['totalResults'] >= '1':
                    imagelink = data['items'][random.randint(0, 9)]['link']
                    bot.sendChatAction(chat_id=chat_id, action=telegram.ChatAction.UPLOAD_PHOTO)
                    bot.sendDocument(chat_id=chat_id, filename=requestText + ': ' + imagelink, document=imagelink)
                else:
                    bot.sendMessage(chat_id=chat_id, text='I\'m sorry Dave, I\'m afraid I can\'t do that.\n(Image not found)')

            elif vidType:  # Video Search - YouTube API
                bot.sendChatAction(chat_id=chat_id, action=telegram.ChatAction.TYPING)
                vidurl = 'https://www.googleapis.com/youtube/v3/search?safeSearch=none&type=video&key=' + keyConfig.get\
                    ('Google', 'GCSE_APP_ID') + '&part=snippet&q='
                realUrl = vidurl + requestText.encode('utf-8')
                data = json.load(urllib.urlopen(realUrl))
                if len(data['items']) >= 1:
                    vidlink = data['items'][0]['id']['videoId']
                    bot.sendMessage(chat_id=chat_id, text='https://www.youtube.com/watch?v=' + vidlink + '&type=video')
                else:
                    bot.sendMessage(chat_id=chat_id, text='I\'m sorry Dave, I\'m afraid I can\'t do that.\n(Video not found)')

            elif wType:  # Weather - Yahoo API
                bot.sendChatAction(chat_id=chat_id, action=telegram.ChatAction.TYPING)
                yahoourl = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20" \
                           "in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%27" + requestText.encode('utf-8') + "%27)%20" \
                           "and%20u%3D%27c%27&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"
                result = urllib.urlopen(yahoourl).read()
                data = json.loads(result)
                if data['query']['count'] == 1:
                    weather = data['query']['results']['channel']['item']['condition']
                    forecast = data['query']['results']['channel']['item']['forecast']
                    city = data['query']['results']['channel']['location']['city']
                    astronomy = data['query']['results']['channel']['astronomy']
                    bot.sendMessage(chat_id=chat_id, text=('It is currently ' + weather['text'] + ' in ' + city + ' with a temperature of '
                                                           + weather['temp'] + 'C.\nA high of ' + forecast[0]['high'] + ' and a low of ' +
                                                           forecast[0]['low'] + ' are expected during the day with conditions being ' +
                                                           forecast[0]['text'] + '.\nSunrise: ' + astronomy['sunrise'] + '\nSunset: ' +
                                                           astronomy['sunset']))
                else:
                    bot.sendMessage(chat_id=chat_id, text='I\'m sorry Dave, I\'m afraid I don\'t know that place.')

            elif xType:  # P**n Search - GCSE API
                bot.sendChatAction(chat_id=chat_id, action=telegram.ChatAction.TYPING)
                googurl = 'https://www.googleapis.com/customsearch/v1?&num=10&safe=off&cx=' + keyConfig.get\
                    ('Google', 'GCSE_XSE_ID') + '&key=' + keyConfig.get('Google', 'GCSE_APP_ID') + '&q='
                realUrl = googurl + requestText.encode('utf-8')
                data = json.load(urllib.urlopen(realUrl))
                if data['searchInformation']['totalResults'] >= '1':
                    for item in data['items']:
                        xlink = item['link']
                        if not 'xvideos.com/tags/' in xlink \
                                and not 'xvideos.com/profiles/' in xlink \
                                and not 'pornhub.com/users/' in xlink \
                                and not 'pornhub.com/video/search?search=' in xlink \
                                and not 'xnxx.com/tags/' in xlink:
                            bot.sendMessage(chat_id=chat_id, text=xlink)
                            break
                else:
                    bot.sendMessage(chat_id=chat_id, text='I\'m sorry Dave, you\'re just too filthy.')

            elif dicType:  # Dictionary - DictionaryAPI.net
                bot.sendChatAction(chat_id=chat_id, action=telegram.ChatAction.TYPING)
                dicUrl = 'http://dictionaryapi.net/api/definition/'
                realUrl = dicUrl + requestText.encode('utf-8')
                data = json.load(urllib.urlopen(realUrl))
                if len(data) >= 1:
                    partOfSpeech = data[random.randint(0, len(data)-1)]
                    if len(partOfSpeech['Definitions']) >= 1:
                        definitionText = partOfSpeech['Definitions'][0]
                        bot.sendMessage(chat_id=chat_id, text=requestText.title() + ":\n" + partOfSpeech['PartOfSpeech'] + ".\n\n" + definitionText)
                    else:
                        bot.sendMessage(chat_id=chat_id, text='I\'m sorry Dave, I\'m afraid I can\'t find any definitions for the word ' + requestText + '.')
                else:
                    bot.sendMessage(chat_id=chat_id, text='I\'m sorry Dave, I\'m afraid I can\'t find any definitions for the word ' + requestText + '.')

            elif urbanDicType:  # Urban Dictionary - Urban API
                bot.sendChatAction(chat_id=chat_id, action=telegram.ChatAction.TYPING)
                dicurl = 'http://api.urbandictionary.com/v0/define?term='
                realUrl = dicurl + requestText.encode('utf-8')
                data = json.load(urllib.urlopen(realUrl))
                if len(data['list']) >= 1:
                    resultNum = data['list'][random.randint(0, len(data['list'])-1)]
                    bot.sendMessage(chat_id=chat_id, text='Urban Definition For ' + requestText.title() + ":\n" + resultNum['definition'] + '\n\nExample:\n' + resultNum['example'])
                else:
                    bot.sendMessage(chat_id=chat_id, text='I\'m sorry Dave, I\'m afraid I can\'t find any urban definitions for ' + requestText)

            elif placeType:  # Google Maps Places API
                bot.sendChatAction(chat_id=chat_id, action=telegram.ChatAction.FIND_LOCATION)
                mapsUrl = 'https://maps.googleapis.com/maps/api/place/textsearch/json?key=' + keyConfig.get('Google', 'GCSE_APP_ID') + '&location=-30,30&radius=50000&query='
                realUrl = mapsUrl + requestText.encode('utf-8')
                data = json.load(urllib.urlopen(realUrl))
                if len(data['results']) >= 1:
                    latNum = data['results'][0]['geometry']['location']['lat']
                    lngNum = data['results'][0]['geometry']['location']['lng']
                    bot.sendLocation(chat_id=chat_id, latitude=latNum, longitude=lngNum)
                else:
                    bot.sendMessage(chat_id=chat_id, text='I\'m sorry Dave, I\'m afraid I can\'t find any places for ' + requestText)

            elif translateType:  # Google Translate API
                bot.sendChatAction(chat_id=chat_id, action=telegram.ChatAction.FIND_LOCATION)
                translateUrl = 'https://www.googleapis.com/language/translate/v2?key=' + keyConfig.get('Google', 'GCSE_APP_ID') + '&target=en&q='
                realUrl = translateUrl + requestText.encode('utf-8')
                data = json.load(urllib.urlopen(realUrl))
                if len(data['data']['translations']) >= 1:
                    translation = data['data']['translations'][0]['translatedText']
                    detectedLanguage = data['data']['translations'][0]['detectedSourceLanguage']
                    languagesList = json.load(urllib.urlopen('https://www.googleapis.com/language/translate/v2/languages?target=en&key=' + keyConfig.get('Google', 'GCSE_APP_ID')))['data']['languages']
                    detectedLanguageSemanticName = [lang for lang in languagesList
                                                    if lang['language'] == detectedLanguage][0]['name']

                    bot.sendMessage(chat_id=chat_id, text="Detected language: " + detectedLanguageSemanticName + "\nMeaning: " + translation.title())
                else:
                    bot.sendMessage(chat_id=chat_id, text='I\'m sorry Dave, I\'m afraid I can\'t find any translations for ' + requestText)

            elif mcType:  # mcstatus API
                bot.sendChatAction(chat_id=chat_id, action=telegram.ChatAction.TYPING)
                server = MinecraftServer.lookup("41.86.100.15:10050")
                status = server.status()
                latency = server.ping()
                query = server.query()
                bot.sendMessage(chat_id=chat_id, text=("The server has {0} players and replied in {1} ms".format(status.players.online, status.latency)))
            else:
                pass  # bot.sendMessage(chat_id=chat_id, text='Hey Boet! Use a valid command next time...')

    return update_id
Beispiel #56
0
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from mcstatus import MinecraftServer
from geopy.geocoders import Nominatim

import forecastio

import logging
import sys
import os
import pickle
import time
import random

api_key = "key"
moduledir = "{0}/modules/".format(os.getcwd())
server = MinecraftServer.lookup("ip")
TOKEN = 'TOKEN'
forecast_info = {}
modules = {}
dp = ""

secret_words = ["unique", "keyboard", "computer", "certificate", "morning", "sunshine", "space", "display", "checker", "music", "pineapple", "insane", "massive", "nice"]


################
####  TODO  ####
################
#
# Todo list fucntion
#    - add and remove items
#    - mark as complete
import json, sys
from mcstatus import MinecraftServer

ip_port = sys.argv[1]

# If you know the host and port, you may skip this and use MinecraftServer("example.org", 1234)
server = MinecraftServer.lookup(ip_port)

try:
    status = server.status()
    print(json.dumps(status.raw))
except:
    print(json.dumps({"error": "Can't get status."}))
'''
Created on Oct 5, 2015

@author: tylerstaut
'''


from mcstatus import MinecraftServer

# If you know the host and port, you may skip this and use MinecraftServer("example.org", 1234)
server = MinecraftServer.lookup("173.31.75.242")

# 'status' is supported by all Minecraft servers that are version 1.7 or higher.
status = server.status()
print("The server has {0} players and replied in {1} ms".format(status.players.online, status.latency))

# 'ping' is supported by all Minecraft servers that are version 1.7 or higher.
# It is included in a 'status' call, but is exposed separate if you do not require the additional info.
latency = server.ping()
print("The server replied in {0} ms".format(latency))

# 'query' has to be enabled in a servers' server.properties file.
# It may give more information than a ping, such as a full player list or mod information.
query = server.query()
print("The server has the following players online: {0}".format(", ".join(query.players.names)))

        


        
            #Exiting Script
            sys.exit()
# Attempting to import mcstatus library. If it is not installed the script will print the notes again.
try:
  from mcstatus import MinecraftServer
except:
    errornotes()


'''def start():
    try:
        server = MinecraftServer.lookup("cheatsallowed.ddns.net:25565")
    except:
        start()'''
#I left my minecraft server's hostname for a test.
server = MinecraftServer.lookup("cheatsallowed.ddns.net:25565")
#this clears the terminal window
print(chr(27) + "[2J")
'''start()'''
#Then we get the status and make 2 strings to print
status = server.status()
statusln1 = ("Players:{0}".format(status.players.online, status.latency))
statusln2 = ("Ping:{1}ms".format(status.players.online, status.latency))
print statusln1
print statusln2
#A loop starts and about every 60 secoonds the terminal is refreshed
while True:
    #Gets the second constantly
    s = strftime("%S")
    # 'status' is supported by all Minecraft servers that are version 1.7 or higher.
    #try: is run in case the server becomes un reachable and prints an error message