-
Posts
1,279 -
Joined
-
Last visited
-
Days Won
3
Posts posted by Disinterpreter
-
-
- Popular Post
- Popular Post
I often see how people are trying to start server using really strange solutions. So I thought "I need to make a good tutorial", let's get it!
You need a Linux server (I use Debian 10) and installed the server.
Usually I put the server in /opt directory, in this tutorial we do it same.
Part One: Installing the server
Let's start to install pure Multi Theft Auto linux server. As a joke from bashorg said: "it only takes three commands to install Gentoo", you have to put only two commands
apt install unzip wget https://linux.multitheftauto.com/dl/multitheftauto_linux_x64.tar.gz && \ tar xvf multitheftauto_linux_x64.tar.gz && \ rm multitheftauto_linux_x64.tar.gz &&\ cd multitheftauto_linux_x64/mods/deathmatch/ && \ wget https://linux.multitheftauto.com/dl/baseconfig.tar.gz && \ tar xvf baseconfig.tar.gz && \ mv baseconfig/* . && \ rm -rf ./baseconfig/ && \ mkdir resources && cd resources && \ wget https://mirror.multitheftauto.com/mtasa/resources/mtasa-resources-latest.zip && \ unzip mtasa-resources-latest.zip && \ rm mtasa-resources-latest.zip && \ cd ../../../ && chmod +x ./mta-server64
What are about these commands?
- Downloading and unpacking mta server binaries
- Downloading and unpacking default configs
- Downloading and unpacking resources
Part 2: Daemonization
Many of tutorials was written when systemd isn't exists. But not today.
Let's make a systemd unit.
Before we're starting to do it, we need to check one thing. Basically MTA Server has ncurses UI, that's can be inconvenient for daemons, so we have to check flags.
Okkay! We take them all!
There are a lot of guides how to make different systemd units, but I've made the config for you. You only need to put the file into /etc/systemd/system/multitheftauto.service
[Unit] Description=Multi Theft Auto Dedicated server After=network.target StartLimitIntervalSec=0 [Service] Type=simple Restart=always RestartSec=1 User=root WorkingDirectory=/opt/multitheftauto_linux_x64 ExecStart=/opt/multitheftauto_linux_x64/mta-server64 -t -n -u [Install] WantedBy=multi-user.target
And make systemd reload the configs
Quotesystemd daemon-reload
Need video?
Seems like you're done all of my steps. What's next?
There are good commands for management the unit
1. journalctl -u multitheftauto -n -f 2. systemctl enable multitheftauto 3. systemctl stop multitheftauto 4. systemctl restart multitheftauto 5. systemctl start multitheftauto 6. systemctl status multitheftauto 1. Reads logs in the stream 2. Enable the unit (after rebooting the server the unit will start) 3,4,5 Stop/restart/start the unit (the server) 6. Status of the unit (is it running? Stopped? and last lines from the std out)
More info you may read here: https://www.freedesktop.org/software/systemd/man/journalctl.html
and here: https://www.freedesktop.org/software/systemd/man/systemctl.html
- 7
-
On 11/07/2021 at 11:11, SanMartin said:
потому ищу таких же энтузиастов как я.
Я готов взяться за помощь (серверсайд), если весь код будет свободным ПО под лицензией AGPLv3
-
- Popular Post
- Popular Post
Part 0; Preamble
At the moment we have a long discussion about databases in the MTA Community, a huge part of the Team thinks that DB-drivers must be only as modules, but right now, we have only RDBMS databases(SQLite and MySQL). It isn’t enough for many dynamic MTA servers.
So, I want to suggest an interesting solution to this problem, so let’s get started!
Part 1; Tarantool
When we think about DODBMS the first variant of this is MongoDB. MongoDB works well with JS, like nodejs, but I want to present to you the DODBMS which work with Lua.
This database is sometimes similar to MongoDB, but it works only with Lua(and SQL but I don’t get it). You can put the data there, get it, and write functions. Cool! And this DBMS is used in production, the developer of this DB is MailRu Group, so, take my word for it, these clients are serious guys, especially MasterCard.
Part 1.1: Setting and installing Tarantool
https://www.tarantool.io/en/download/os-installation/debian/
After installing launch the command `tarantool` and load global config with command box.cfg{}
Part 1.2: The space’s markup
I'll try to make a managed alcohol list, so watch my hands
-- a sequence box.schema.sequence.create('drinks_seq', { if_not_exists = true })
-- a space, like a table in MySQL box.schema.create_space('drinks', { if_not_exists = true, format={ { name = 'id', type = 'unsigned'}, { name = 'name', type = 'string'}, { name = 'count', type = 'unsigned'}} })
-- an index box.space.drinks:create_index('pk', { parts = { 'id' }, if_not_exists = true })
-- Insert 13 bottles of beer box.space.drinks:insert{box.sequence.drinks_seq:next(), 'Beer', 13}
That’s all, the cascade has done!
Part 1.3: Fall in love workarounds
Without spoilers, our workaround is fetchRemote, so, do the server.
Any solution from: https://github.com/tarantool/http#installation
And take a look to my code:
#!/usr/bin/env tarantool local http_router = require('http.router') local http_server = require('http.server') local json = require('json') -- Load default config box.cfg{} -- Start the server -- WARNING: 0.0.0.0 listen the port for all interfaces, don't do it, use 127.0.0.1! local httpd = http_server.new('0.0.0.0', 3820, { log_requests = true, log_errors = true }) local router = http_router.new() -- GET endpoint, returns data from database router:route({ path = '/drinks', method = 'GET' }, function() -- Load space local dspace = box.space.drinks -- Select all, too risky read more about select and limits -- Here: https://www.tarantool.io/en/doc/latest/reference/reference_lua/box_index/select/ local drinks = dspace:select{} return {status = 200, body = json.encode(drinks), headers = { ['content-type'] = 'application/json; charset=utf8' }} end ) -- PUT endpoint, add data to the database router:route({ path = '/drinks', method = 'PUT' }, function(req) local dspace = box.space.drinks -- [1] is https://github.com/multitheftauto/mtasa-blue/issues/1073 local body = req:json()[1] -- box.sequence.drinks_seq:next() is auto-increment local drinks = dspace:insert{box.sequence.drinks_seq:next(), body.type, tonumber(body.count)} if drinks then return {status = 200, body = json.encode(drinks), headers = { ['content-type'] = 'application/json; charset=utf8' }} else return {status = 200, body = '{"status": "something went wrong"}', headers = { ['content-type'] = 'application/json; charset=utf8' }} end end ) -- POST endpoint, edit the data in the database router:route({ path = '/drinks', method = 'POST' }, function(req) local dspace = box.space.drinks -- [1] is https://github.com/multitheftauto/mtasa-blue/issues/1073 local body = req:json()[1] -- Well... Complicated thing (not much) -- update(key, {{ = is assignment, number of field, value}, ...}) local drinks = dspace:update(tonumber(body.id), {{'=', 3, tonumber(body.count)}}) if drinks then return {status = 200, body = json.encode(drinks), headers = { ['content-type'] = 'application/json; charset=utf8' }} else return {status = 200, body = '{"status": "something went wrong"}', headers = { ['content-type'] = 'application/json; charset=utf8' }} end end ) httpd:set_router(router) httpd:start()
After that we have to start it.
cd /path/to/saved/script && chmod +x ./server.lua && ./server.lua
Part 2.0: MTA resource
The communication side will be simple command drinks with interactive options.
local url = "http://127.0.0.1:3820/drinks" -- GET endpoint function showDrinks() local sendOptions = { queueName = "tarantool.drinks.get", method = "GET", } local successRemote = fetchRemote(url, sendOptions, function (responseData, responseInfo) local error = responseInfo.statusCode if error == 200 then print (responseData) end end ) end -- PUT endpoint function addDrinks(arg) local data = { type = tostring(arg[1]), count = tonumber(arg[2]) } local sendOptions = { queueName = "tarantool.drinks.add", postData = toJSON(data), method = "PUT", } local successRemote = fetchRemote(url, sendOptions, function (responseData, responseInfo) local error = responseInfo.statusCode if error == 200 then print ("Successfully added") end end ) end -- POST endpoint function updateDrinks(arg) local data = { id = tonumber(arg[1]), count = tonumber(arg[2]) } local sendOptions = { queueName = "tarantool.drinks.update", postData = toJSON(data), method = "POST", } local successRemote = fetchRemote(url, sendOptions, function (responseData, responseInfo) local error = responseInfo.statusCode if error == 200 then print ("Successfully updated") end end ) end -- Command handler addCommandHandler("drinks", function(ply, cmd, ...) local arg = {...} local subcmd = arg[1] -- subcmd is useless in the table table.remove(arg, 1) -- case/switch if subcmd == 'list' then showDrinks() end if subcmd == 'add' then addDrinks(arg) end if subcmd == 'update' then updateDrinks(arg) end end)
And… That’s all. Look at the screenshot, it works!
Conclusion: By the idea it must be simple only in resource without HTTP middleware, but at the moment it is impossible due to slow moving MTA progress, so if you like my tutorial and want to push my solution without middleware push and talk about it there.
A solution without workaround: https://github.com/multitheftauto/mtasa-blue/issues/2208
- 7
-
1 hour ago, Ushnurcev said:
Как можно проверить смотрит ли игрок на определённый объект?
Нужно использовать colShape? Если кто-то понимает как это реализовать, приведите пожалуйста пример с поясненьями. Спасибо.Попробуй кинуть от головы
https://wiki.multitheftauto.com/wiki/ProcessLineOfSight
Или
- 1
-
1 hour ago, TheVadiaCool said:
Я выключал почти все ресурсы, все тоже самое, не могу найти причину. ДАЖЕ если бы были циклы, то перфоманс браузер показал бы это. Я специально создал цикл и проверил - нагрузка была показана в браузере.
Причину найти не могу.Может дело в дешманском хостинге с заниженными характиристиками?
-
51 minutes ago, TheVadiaCool said:
От кода сценария? Можно подробнее?
Ну если ты натыкаешь бесконечных циклов, то CPU от этого вырастит, например. Так же иногда в простое сервер всё же делает какие-то вещи(но обычно на гарфиках это пики вего лишь).
-
11 hours ago, TheVadiaCool said:
Здравствуйте. Столкнулся с такой ситуацией, даже не знаю, является это проблемой или нет. Дело в том, что при простое мой сервер использует 220 MHz процессора (хостинг куплен с тарифом на 1100 MHz), соответственно, в панели хостинга показывает, что процессор нагружен на 19% (220 MHz от 1100 MHz). Притом, что игроков на сервере нет. Искал причину в Resource Browser'e, но там мне показывает, что нагрузки нет ВООБЩЕ, лишь занята оперативная память. Посмотрел и внутри самой игры с помощью IPB (Ingame Perfomance Browser), но там написано, что нагрузка процессора меньше 1%. И эти 19% держатся почти постоянно, даже ночью, когда нет СОВСЕМ никакой нагрузки от игроков. Находясь в игре, это нагрузку никак не ощутить, все сообщения отправляются быстро, задержек не имеется. Скажите, пожалуйста, норма ли это? Возможно, что сервер сам по себе тратит ресурсы, просто будучи запущенным?
Зависит от кода сценария. Да, может.
-
On 28/10/2020 at 12:08, Erema93 said:
В логах пусто. Сервер тупо закрывается сам без ошибок.
Ну тогда я тут ничего сказать не могу. Надо изучать. AMX'у что-то не нравится конкретно в моде. Это надо изучать.
-
On 26/10/2020 at 17:29, Erema93 said:
Положил файл из архива куда указал, теперь сервер после запуска сам закрывается
почитай логи
-
Возьми архив отсюда https://github.com/multitheftauto/amx/issues/55
И положи сюда
mods\deathmatch\
-
On 12/10/2020 at 12:32, SerjLab said:
А вы это умеете делать я просто так и не понял почему выдает ошибку при использовании стандартного билда, может чтото отключить надо в исходнике? Сможете подсказать? может ВК или дискорд если что?
Да. Я умею отказываться от кастомного лаунчера. Пользуйтесь тем что предоставила МТА. В противном случае, на данный момент, вы нарушаете GNU/GPLv3 и я не думаю, что мне разрешено оказывать вам помощь.
-
On 28/08/2020 at 15:48, FJason said:
Улучшенная система прокачки персонажа, сундуки, карта, новая теория пространства.
https://vk.com/@mtami-teoriya-prostranstvaПодчеркну маленькую мелочь, никто не пишет символ $ после числа. $ всегда пишется перед числом.
-
1 hour ago, scripter1 said:
можешь исправленный код плз скинуть?
Не особо тебя понимаюНе могу. Не я же программист этого кода. Я только подсказал путь для решения.
-
5 minutes ago, scripter1 said:
внутри функции pickupJobTrudoustroistvo? или в функции m1hit?
@Disinterpreter
Нет, смотри, у тебя сейчас маркер находится внутри pickupJobTrudoustroistvo, однако addEventHandler находится в глобальном окружении. Тебе нужно чтобы addEventHandler видел твой маркер, как тебе посоветовали выше, ты можешь блок с addEventHandler добавить внутрь функции pickupJobTrudoustroistvo. Ну или есть десяток других способов.
-
3 hours ago, scripter1 said:
Хм, а как это пофиксить собственно?
сделать доступ для m1
-
У тебя
addEventHandler("onMarkerHit", m1, m1hit)
не может увидеть m1, так как тот локален и находится внутри функции.
-
MTA справедливо относится к кастомным билдам на своей платформе.
Вы можете не использовать кастомные билды и тогда получите весь античит. В противном случае, вам нужно писать его самим на C++ и что-то на Lua.
- 1
-
On 20/06/2020 at 14:43, Voter said:
Есть подсветка синтаксиса MTASA для Sublime Text 3?
-
On 16/06/2020 at 14:16, Riplle said:
Всем здравствуйте помогите пожалуйста мне с моей проблемой.Игрокам которые заходят на сервер,выдаётся админ панель.Как это решить?
Проверьте acl.xml
-
On 14/06/2020 at 10:49, Krackeen_777 said:
Значит, создал сервер через пункт "Создать сервер" в меню МТА, хотя я могу запустить и MTAServer.exe . Дело в том, что где-то я вычитал, что если запускать сервер через меню, то на него смогут зайти игроки с интернета, а не только по локальной сети, что для меня не мало важно. Значит, запустил сервер через меню, мта подключается к серверу, и уже через пару секунд пишет: "Время подключения к локальгому серверу истекло. Откройте консоль, чтобы узнать подробности. ", открыл консоль, а там написано:
сервер запущен
ожидается подключение игроков
я подлючился
я отключился
сервер остаровлен
И что мне теперь делать? На хостинги денег нет. Роутер порты не открывает(пробовал уже не раз). Играть через Hamachi не получилось...
"Создать сервер" из меню включает сервер из папке server. Между ними нет разницы.
-
On 04/06/2020 at 17:07, makeevip said:
addEventHandler ( "onPlayerCommand", корень, функция (ЦМД)
локальный URL = "http://api.vk.com/method/messages.send?&chat_id=1&message=ЖОПА&v=5.89&access_token=ТУТ БЫЛ ТОКЕН"
fetchRemote (URL - адрес, 10 , 10000, функция (data, errorCode, arguments)
outputDebugString ("data:" ..tostring (data) .. "Error:" ..errorCode .. "Args:" ..tostring (arguments))
end, "", правда)
конец)
с https пишет ошибку 1
с http молчит, но в ответ присылает этоЯ вынужден был вмешаться и отредактировать сообщение. Так как там был личный секретный токен.
-
6 hours ago, Maladoy.16 said:
kak podkliuciti mysql?
вводишь в свой конфиг айпи логин и пароль
- 1
-
On 12/03/2020 at 16:07, Maladoy.16 said:
[2020-03-12 14:44:00] WARNING: [gameplay]\mysql\server.Lua:8: Bad usage @ 'dbConnect' [Can't connect to MySQL server on 'localhost' (10061)]
[2020-03-12 14:44:00] ERROR: [gameplay]\mysql\server.Lua:12: [MYSQL][ERROR] Connection failed!
[2020-03-12 14:44:08] WARNING: [gameplay]\mysql\server.Lua:8: Bad usage @ 'dbConnect' [Can't connect to MySQL server on 'localhost' (10061)]
[2020-03-12 14:44:08] ERROR: [gameplay]\mysql\server.Lua:12: [MYSQL][ERROR] Connection failed!
[2020-03-12 14:44:08] WARNING: [gameplay]\mysql\server.Lua:35: Bad argument @ 'dbQuery' [Expected db-connection at argument 3, got boolean]
[2020-03-12 14:44:15] WARNING: [gameplay]\mysql\server.Lua:8: Bad usage @ 'dbConnect' [Can't connect to MySQL server on 'localhost' (10061)]
[2020-03-12 14:44:15] ERROR: [gameplay]\mysql\server.Lua:12: [MYSQL][ERROR] Connection failed!
[2020-03-12 14:44:22] WARNING: [gameplay]\mysql\server.Lua:8: Bad usage @ 'dbConnect' [Can't connect to MySQL server on 'localhost' (10061)]
[2020-03-12 14:44:22] ERROR: [gameplay]\mysql\server.Lua:12: [MYSQL][ERROR] Connection failed!Ribiata Spasite
Проверь MySQL соединение.
-
On 18/03/2020 at 15:38, Ellesse said:
Что бы не делать ресурс а напрямую через anim.img
Они же не будут синхранизироваться. Какой в этом смысл?
Which OS is best for the server?
in Servers
Posted
From
https://github.com/multitheftauto/mtasa-blue/issues/2538#issuecomment-1029828744
Is anyone prove it for today? Seems like a bull:~ (sorry).